import MHeader from '@/components/m-header';
import MSticky from '@/components/m-sticky';
import {
  computed,
  defineComponent,
  onMounted,
  reactive,
  ref,
  watch
} from 'vue';
import styles from './index.module.less';
import { useRoute } from 'vue-router';
import request from '@/helpers/request';
import { useEventListener, useWindowScroll } from '@vueuse/core';
import MEmpty from '@/components/m-empty';
import { Button } from 'vant';
import { browser } from '@/helpers/utils';

export default defineComponent({
  name: 'unit-detail',
  setup() {
    const route = useRoute();

    const forms = reactive({
      detailId: route.query.detailId,
      loading: false,
      background: 'transparent',
      color: '#fff',
      dataInfo: {} as any,
      title: ' ',
      listKnowledge: [] as any,
      prevDetailId: '',
      nextDetailId: ''
    });

    const getList = async () => {
      forms.loading = true;
      try {
        const { data } = await request.get(
          '/edu-app/lessonCoursewareKnowledgeDetail/detail/' + forms.detailId
        );
        forms.dataInfo = data;
        forms.title = data.name;
      } catch {
        //
      }
      forms.loading = false;
    };

    const getPointList = async () => {
      try {
        const params: any = {
          lessonCoursewareId: route.query.lessonCoursewareId
        };
        if (browser().ios) {
          params.platform = 'iOS-STUDENT';
          params.verson = route.query.verson || '1.0.8';
        }
        const { data } = await request.post(
          '/edu-app/lessonCoursewareDetail/listKnowledge',
          {
            data: params
          }
        );

        forms.listKnowledge = data || [];
      } catch {
        //
      }
    };

    const upDisabled = computed(() => {
      const listKnowledge = forms.listKnowledge || [];
      let parentIndex = listKnowledge.findIndex(
        (item: any) => item.id === forms.dataInfo?.lessonCoursewareDetailId
      );
      const parentItem = listKnowledge.find(
        (item: any) => item.id === forms.dataInfo?.lessonCoursewareDetailId
      );
      if (!parentItem) {
        return true;
      }
      let detailIndex =
        parentItem?.lessonCoursewareDetailKnowledgeDetailList?.findIndex(
          (item: any) => item.id == forms.detailId
        );
      let lessonStatus = false; // 当前章节上面是否有内容
      let lessonCoursewareDetailId = '';
      while (detailIndex >= 0) {
        detailIndex--;
        if (detailIndex >= 0) {
          const tempItem =
            parentItem?.lessonCoursewareDetailKnowledgeDetailList?.[
              detailIndex
            ];
          if (tempItem.id) {
            lessonStatus = true;
            lessonCoursewareDetailId = tempItem.id;
          }
        }
        if (lessonStatus) {
          break;
        }
      }
      // 判断当前章节上面课程是否有内容，否则往上一个章节走
      if (lessonStatus) {
        forms.prevDetailId = lessonCoursewareDetailId;
        return false;
      }

      let prevLessonStatus = false;
      while (parentIndex >= 0) {
        parentIndex--;
        const tempDetail =
          listKnowledge[parentIndex]
            ?.lessonCoursewareDetailKnowledgeDetailList || [];

        let tempLessonLength = tempDetail.length;
        while (tempLessonLength > 0) {
          if (tempDetail[tempLessonLength - 1]) {
            prevLessonStatus = true;
            lessonCoursewareDetailId = tempDetail[tempLessonLength - 1].id;
          }
          tempLessonLength--;
          if (prevLessonStatus) {
            break;
          }
        }
        if (prevLessonStatus) {
          break;
        }
      }
      if (prevLessonStatus) {
        forms.prevDetailId = lessonCoursewareDetailId;
      }
      return !prevLessonStatus;
    });

    const downDisabled = computed(() => {
      const listKnowledge = forms.listKnowledge || [];
      let parentIndex = listKnowledge.findIndex(
        (item: any) => item.id === forms.dataInfo?.lessonCoursewareDetailId
      );
      const parentItem = listKnowledge.find(
        (item: any) => item.id === forms.dataInfo?.lessonCoursewareDetailId
      );
      if (!parentItem) {
        return true;
      }
      let detailIndex =
        parentItem?.lessonCoursewareDetailKnowledgeDetailList?.findIndex(
          (item: any) => item.id == forms.detailId
        );
      let lessonStatus = false; // 当前章节上面是否有内容
      let lessonCoursewareDetailId = '';
      while (
        detailIndex <
        parentItem?.lessonCoursewareDetailKnowledgeDetailList.length - 1
      ) {
        detailIndex++;
        if (detailIndex >= 0) {
          const tempItem =
            parentItem?.lessonCoursewareDetailKnowledgeDetailList?.[
              detailIndex
            ];
          if (tempItem.id) {
            lessonStatus = true;
            lessonCoursewareDetailId = tempItem.id;
          }
        }
        if (lessonStatus) {
          break;
        }
      }

      // 判断当前章节上面课程是否有内容，否则往上一个章节走
      if (lessonStatus) {
        forms.nextDetailId = lessonCoursewareDetailId;
        return false;
      }

      let nextLessonStatus = false;
      while (parentIndex <= listKnowledge.length - 1) {
        parentIndex++;
        const tempDetail =
          listKnowledge[parentIndex]
            ?.lessonCoursewareDetailKnowledgeDetailList || [];

        let tempLessonLength = 0;
        while (tempLessonLength <= tempDetail.length - 1) {
          if (tempDetail[tempLessonLength]) {
            nextLessonStatus = true;
            lessonCoursewareDetailId = tempDetail[tempLessonLength].id;
          }
          tempLessonLength++;
          if (nextLessonStatus) {
            break;
          }
        }

        if (nextLessonStatus) {
          break;
        }
      }
      if (nextLessonStatus) {
        forms.nextDetailId = lessonCoursewareDetailId;
      }
      return !nextLessonStatus;
    });

    // 切换
    const handleChanage = async (type: string) => {
      if (type === 'up') {
        forms.detailId = forms.prevDetailId;
        await getList();
      } else if (type === 'down') {
        forms.detailId = forms.nextDetailId;
        await getList();
      }
    };

    onMounted(async () => {
      useEventListener(document, 'scroll', () => {
        const { y } = useWindowScroll();
        if (y.value > 52) {
          forms.background = '#fff';
          forms.color = '#323333';
        } else {
          forms.background = 'transparent';
          forms.color = '#fff';
        }
      });

      // __initMove();

      await getList();
      await getPointList();
    });
    return () => (
      <div class={styles.knowledgeLibrary}>
        <MSticky position="top">
          <MHeader
            border={false}
            background={forms.background}
            color={forms.color}
            title={forms.title}></MHeader>
        </MSticky>

        <div class={[styles.containerSection, styles.woringSection]}>
          {forms.dataInfo?.desc && (
            <div
              class={styles.woringContent}
              v-html={forms.dataInfo.desc}></div>
          )}
          {!forms.dataInfo?.desc && !forms.loading && (
            <div class={styles.woringContent}>
              <MEmpty description="暂无内容" style={{ paddingTop: '40px' }} />
            </div>
          )}
        </div>

        <MSticky position="bottom">
          <div class={[styles.stickBtnGroup]}>
            <Button
              round
              class={styles.prevBtn}
              disabled={upDisabled.value}
              onClick={() => handleChanage('up')}></Button>
            <Button
              round
              disabled={downDisabled.value}
              class={styles.nextBtn}
              onClick={() => handleChanage('down')}></Button>
          </div>
        </MSticky>
      </div>
    );
  }
});
