import { defineComponent, onMounted, reactive, ref, watch } from 'vue';
import styles from './index.module.less';
import {
  NButton,
  NCarousel,
  NIcon,
  NImage,
  NInput,
  NModal,
  NScrollbar,
  NSelect,
  NSpace,
  NSpin,
  useMessage
} from 'naive-ui';
import { usePrepareStore } from '/src/store/modules/prepareLessons';
import add from '@/views/studentList/images/add.png';
import iconSlideRight from '../../../images/icon-slide-right.png';
import CoursewareType from '../../../model/courseware-type';
import TheEmpty from '/src/components/TheEmpty';
import RelatedClass from '../../../model/related-class';
import { state } from '/src/state';
import { useResizeObserver } from '@vueuse/core';
import AttendClass from '/src/views/prepare-lessons/model/attend-class';
import {
  api_addByOpenCourseware,
  api_teacherChapterLessonCoursewareRemove,
  api_queryOpenCoursewareByPage,
  api_updateCoursewareInfo,
  teacherChapterLessonCoursewareList,
  courseScheduleStart
} from '../../../api';
import { useRoute, useRouter } from 'vue-router';
import TheMessageDialog from '/src/components/TheMessageDialog';
import { eventGlobal, fscreen } from '/src/utils';
import PreviewWindow from '/src/views/preview-window';

export default defineComponent({
  name: 'courseware-presets',
  emits: ['change'],
  setup(props, { emit }) {
    const prepareStore = usePrepareStore();
    const message = useMessage();
    const route = useRoute();
    const router = useRouter();
    const localStorageSubjectId = localStorage.getItem(
      'prepareLessonSubjectId'
    );

    const forms = reactive({
      // 选取参数带的，后取缓存
      messageLoading: false,
      subjectId: route.query.subjectId
        ? Number(route.query.subjectId)
        : localStorageSubjectId
        ? Number(localStorageSubjectId)
        : '',
      courseScheduleSubjectId: route.query.courseScheduleSubjectId,
      classGroupId: route.query.classGroupId,
      preStudentNum: route.query.preStudentNum,
      bodyWidth: '100%',
      loading: false,
      openLoading: false,
      showRelatedClass: false,
      tableList: [] as any,
      openTableList: [] as any,
      selectItem: {} as any,
      editTitleVisiable: false,
      editTitle: null,
      editBtnLoading: false,
      preRemoveVisiable: false,
      carouselIndex: 0,
      showAttendClass: false,
      attendClassType: 'change', //
      attendClassItem: {} as any,
      previewModal: false,
      previewParams: {
        type: '',
        courseId: '',
        subjectId: '',
        detailId: ''
      } as any
    });

    const getCoursewareList = async () => {
      forms.loading = true;
      try {
        // 判断是否有选择对应的课件 或声部
        if (!prepareStore.getSelectKey) return (forms.loading = false);
        const { data } = await teacherChapterLessonCoursewareList({
          subjectId: prepareStore.getSubjectId,
          coursewareDetailKnowledgeId: prepareStore.getSelectKey
        });
        if (!Array.isArray(data)) {
          return;
        }
        const tempList: any = [];
        data.forEach((item: any) => {
          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
          });
        });
        forms.tableList = tempList;
      } catch {
        //
      }
      forms.loading = false;
    };

    const getOpenCoursewareList = async () => {
      // 查询公开课件列表
      forms.openLoading = true;
      try {
        // 判断是否有选择对应的课件 或声部
        if (!prepareStore.getSelectKey) return (forms.openLoading = false);
        const { data } = await api_queryOpenCoursewareByPage({
          subjectId: prepareStore.getSubjectId,
          coursewareDetailKnowledgeId: prepareStore.getSelectKey,
          page: 1,
          rows: 20
        });
        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
          });
        });

        forms.openTableList = chunkArray(tempList, 4);
      } catch {
        //
      }
      forms.openLoading = false;
    };

    const chunkArray = (array: any, size: number) => {
      const result = [];
      for (let i = 0; i < array.length; i += size) {
        result.push(array.slice(i, i + size));
      }
      return result;
    };

    // 监听选择的key 左侧选择了其它的课
    watch(
      () => [prepareStore.getSelectKey, prepareStore.getSubjectId],
      async () => {
        await getCoursewareList();
        await getOpenCoursewareList();
      }
    );

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

    watch(
      () => prepareStore.getSubjectList,
      () => {
        checkSubjectIds();
      }
    );

    const checkSubjectIds = () => {
      const subjectList = prepareStore.getSubjectList;

      // 并且没有声部时才会更新
      if (subjectList.length > 0) {
        // 并且声部在列表中
        const localStorageSubjectId = localStorage.getItem(
          'prepareLessonSubjectId'
        );
        // // 先取 上次上课声部，在取班级声部 最后取缓存
        let subjectId = null;
        let index = -1;
        if (forms.courseScheduleSubjectId) {
          // 判断浏览器上面是否有
          index = subjectList.findIndex(
            (subject: any) => subject.id == forms.courseScheduleSubjectId
          );
          if (index >= 0) {
            subjectId = Number(forms.courseScheduleSubjectId);
          }
        }
        // 判断班级上面声部 & 还没有声部
        if (forms.subjectId && !subjectId) {
          // 判断浏览器上面是否有
          index = subjectList.findIndex(
            (subject: any) => subject.id == forms.subjectId
          );
          if (index >= 0) {
            subjectId = Number(forms.subjectId);
          }
        }
        // 缓存声部 & 还没有声部
        if (localStorageSubjectId && !subjectId) {
          // 判断浏览器上面是否有
          index = subjectList.findIndex(
            (subject: any) => subject.id == localStorageSubjectId
          );
          if (index >= 0) {
            subjectId = Number(localStorageSubjectId);
          }
        }
        if (subjectId && index >= 0) {
          prepareStore.setSubjectId(subjectId);
          // forms.subjectId = subjectId;
        } else {
          // 判断是否有缓存
          prepareStore.setSubjectId(subjectList[0].id);
          // forms.subjectId = subjectList[0].id;
        }

        // 保存
        localStorage.setItem(
          'prepareLessonSubjectId',
          prepareStore.getSubjectId as any
        );
      }
    };

    onMounted(async () => {
      prepareStore.setClassGroupId(route.query.classGroupId as any);
      if (!prepareStore.getSubjectId) {
        // 获取教材分类列表
        checkSubjectIds();
      }

      // useResizeObserver(
      //   document.querySelector('#coursewarePresets') as HTMLElement,
      //   (entries: any) => {
      //     const entry = entries[0];
      //     const { width } = entry.contentRect;
      //     forms.bodyWidth = width + 'px';
      //   }
      // );

      await getCoursewareList();
      await getOpenCoursewareList();
    });

    // 重命名
    const onEditTitleSubmit = async () => {
      try {
        await api_updateCoursewareInfo({
          id: forms.selectItem.id,
          name: forms.editTitle
        });
        message.success('修改成功');
        getCoursewareList();
        // getOpenCoursewareList()
        forms.editTitleVisiable = false;
      } catch {
        //
      }
    };

    // 删除
    const onRemove = async () => {
      forms.messageLoading = true;
      try {
        await api_teacherChapterLessonCoursewareRemove({
          id: forms.selectItem.id
        });
        message.success('删除成功');
        getCoursewareList();
        getOpenCoursewareList();
        forms.preRemoveVisiable = false;
      } catch {
        //
      }
      setTimeout(() => {
        forms.messageLoading = false;
      }, 100);
    };

    // 添加课件
    const onAddCourseware = async (item: any) => {
      if (forms.messageLoading) return;
      forms.messageLoading = true;
      try {
        await api_addByOpenCourseware({ id: item.id });
        message.success('添加成功');
        getCoursewareList();
        getOpenCoursewareList();
      } catch {
        //
      }
      setTimeout(() => {
        forms.messageLoading = false;
      }, 100);
    };

    // 预览上课
    const onPreviewAttend = (id: string) => {
      // 判断是否在应用里面
      if (window.matchMedia('(display-mode: standalone)').matches) {
        state.application = window.matchMedia(
          '(display-mode: standalone)'
        ).matches;
        forms.previewModal = true;
        fscreen();
        forms.previewParams = {
          type: 'preview',
          courseId: id,
          subjectId: prepareStore.getSubjectId,
          detailId: prepareStore.getSelectKey,
          lessonCourseId: prepareStore.getBaseCourseware.id
        };
      } else {
        const { href } = router.resolve({
          path: '/attend-class',
          query: {
            type: 'preview',
            courseId: id,
            subjectId: prepareStore.getSubjectId,
            detailId: prepareStore.getSelectKey,
            lessonCourseId: prepareStore.getBaseCourseware.id
          }
        });
        window.open(href, +new Date() + '');
      }
    };

    const onStartClass = async (item: any, classGroupId: any) => {
      if (classGroupId) {
        // 开始上课
        const res = await courseScheduleStart({
          lessonCoursewareKnowledgeDetailId: prepareStore.selectKey,
          classGroupId: classGroupId,
          useChapterLessonCoursewareId: item.id,
          subjectId: prepareStore.getSubjectId
        });
        if (window.matchMedia('(display-mode: standalone)').matches) {
          state.application = window.matchMedia(
            '(display-mode: standalone)'
          ).matches;
          forms.previewModal = true;
          fscreen();
          forms.previewParams = {
            type: 'class',
            classGroupId: classGroupId,
            courseId: item.id,
            subjectId: prepareStore.getSubjectId,
            detailId: prepareStore.getSelectKey,
            classId: res.data,
            lessonCourseId: prepareStore.getBaseCourseware.id,
            preStudentNum: forms.preStudentNum
          };
        } else {
          const { href } = router.resolve({
            path: '/attend-class',
            query: {
              type: 'class',
              classGroupId: classGroupId,
              courseId: item.id,
              subjectId: prepareStore.getSubjectId,
              detailId: prepareStore.getSelectKey,
              classId: res.data,
              lessonCourseId: prepareStore.getBaseCourseware.id,
              preStudentNum: forms.preStudentNum
            }
          });
          window.open(href, +new Date() + '');
        }
      } else {
        forms.showAttendClass = true;
        forms.attendClassType = 'change';
        forms.attendClassItem = item;
      }
    };

    const carouselRef = ref();
    const onChangeSlide = (type: 'left' | 'right') => {
      if (type === 'left') {
        carouselRef.value?.prev();
      } else if (type === 'right') {
        carouselRef.value?.next();
      }
    };
    return () => (
      <div class={styles.coursewarePresetsContainer}>
        <NScrollbar class={styles.coursewarePresets}>
          <div class={styles.title} id="coursewarePresets">
            <div class={styles.titleLeft}>
              <i class={[styles.icon, styles.iconWork]}></i>
              我的课件
            </div>
          </div>

          <NSpace>
            <NSelect
              placeholder="选择声部"
              class={styles.btnSubjectList}
              options={[
                { name: '全部声部', id: '' },
                ...prepareStore.getSubjectList
              ]}
              labelField="name"
              valueField="id"
              value={prepareStore.getSubjectId}
              onUpdate:value={(val: any) => {
                prepareStore.setSubjectId(val);
                // 保存
                forms.subjectId = val;
              }}
            />
            <NButton
              class={styles.addBtn}
              type="primary"
              onClick={() => {
                eventGlobal.emit('teacher-slideshow', true);
                emit('change', { status: true, type: 'create' });
              }}>
              <NImage
                class={styles.addBtnIcon}
                previewDisabled
                src={add}></NImage>
              创建课件
            </NButton>
          </NSpace>
          <div style={{ overflow: 'hidden' }}>
            <NSpin show={forms.loading}>
              <div class={styles.list}>
                {forms.tableList.map((item: any) => (
                  <div class={[styles.itemWrap, styles.itemBlock, 'row-nav']}>
                    <div class={styles.itemWrapBox}>
                      <CoursewareType
                        operate
                        isEditName
                        item={item}
                        onClick={() => onPreviewAttend(item.id)}
                        onEditName={() => {
                          forms.selectItem = item;
                          forms.editTitle = item.name;
                          forms.editTitleVisiable = true;
                        }}
                        onEdit={() => {
                          //
                          eventGlobal.emit('teacher-slideshow', true);
                          emit('change', {
                            status: true,
                            type: 'update',
                            groupItem: { id: item.id }
                          });
                        }}
                        onStartClass={() =>
                          onStartClass(item, forms.classGroupId)
                        }
                        onDelete={() => {
                          forms.selectItem = item;
                          forms.preRemoveVisiable = true;
                        }}
                      />
                    </div>
                  </div>
                ))}
                {!forms.loading && forms.tableList.length <= 0 && (
                  <TheEmpty class={styles.empty1} />
                )}
              </div>
            </NSpin>
          </div>

          {forms.openTableList.length > 0 && (
            <>
              <div class={[styles.title, styles.line]}>
                <div class={styles.titleLeft}>
                  <i class={[styles.icon, styles.iconCourseware]}></i>
                  相关课件
                  {forms.openTableList.length > 1 && (
                    <span
                      class={styles.more}
                      onClick={() => (forms.showRelatedClass = true)}>
                      查看更多
                      {/* <NIcon size={15}>
                        <svg
                          xmlns="http://www.w3.org/2000/svg"
                          viewBox="0 0 24 24">
                          <path
                            d="M8.59 16.59L13.17 12L8.59 7.41L10 6l6 6l-6 6l-1.41-1.41z"
                            fill="currentColor"></path>
                        </svg>
                      </NIcon> */}
                      <i class={styles.iconP}></i>
                    </span>
                  )}
                </div>

                {forms.openTableList.length > 1 && (
                  <NSpace class={styles.swipeControll}>
                    <div onClick={() => onChangeSlide('left')}>
                      <NImage
                        previewDisabled
                        class={[
                          styles.leftIcon,
                          forms.carouselIndex === 0 && styles.disabled
                        ]}
                        src={iconSlideRight}
                      />
                    </div>
                    <div onClick={() => onChangeSlide('right')}>
                      <NImage
                        class={
                          forms.carouselIndex ==
                            forms.openTableList.length - 1 && styles.disabled
                        }
                        previewDisabled
                        src={iconSlideRight}
                      />
                    </div>
                  </NSpace>
                )}
              </div>

              <NSpin show={forms.openLoading} class={styles.openLoading}>
                <NCarousel
                  slidesPerView={1}
                  loop={false}
                  ref={carouselRef}
                  // style={{ width: forms.bodyWidth }}
                  v-model:currentIndex={forms.carouselIndex}>
                  {forms.openTableList.map((item: any) => (
                    <div class={[styles.list, styles.listSame]}>
                      {item.map((child: any) => (
                        <div
                          class={[
                            styles.itemWrap,
                            styles.itemBlock,
                            'row-nav'
                          ]}>
                          <div class={styles.itemWrapBox}>
                            <CoursewareType
                              isShowOpenFlag={false}
                              isShowAdd
                              isHoverShowAdd={false}
                              item={child}
                              onClick={() => onPreviewAttend(child.id)}
                              onAdd={() => onAddCourseware(child)}
                            />
                          </div>
                        </div>
                      ))}
                    </div>
                  ))}
                </NCarousel>
              </NSpin>
            </>
          )}
        </NScrollbar>

        <NModal
          v-model:show={forms.showRelatedClass}
          preset="card"
          showIcon={false}
          class={['modalTitle background', styles.attendClassModal1]}
          title={'相关课件'}
          blockScroll={false}>
          <RelatedClass
            tableList={forms.tableList}
            subjectList={prepareStore.getSubjectList}
            subjectId={prepareStore.getSubjectId as any}
            coursewareDetailKnowledgeId={prepareStore.getSelectKey}
            onClose={() => (forms.showRelatedClass = false)}
            onAdd={(item: any) => onAddCourseware(item)}
            onClick={(item: any) => {
              onPreviewAttend(item.id);
              forms.showRelatedClass = false;
            }}
          />
        </NModal>

        <NModal
          v-model:show={forms.editTitleVisiable}
          preset="card"
          class={['modalTitle', styles.removeVisiable1]}
          title={'课件重命名'}>
          <div class={styles.studentRemove}>
            <NInput
              placeholder="请输入课件名称"
              v-model:value={forms.editTitle}
              maxlength={15}
              onKeyup={(e: any) => {
                if (e.code === 'ArrowLeft' || e.code === 'ArrowRight') {
                  e.stopPropagation();
                }
              }}
            />

            <NSpace class={styles.btnGroupModal} justify="center">
              <NButton round onClick={() => (forms.editTitleVisiable = false)}>
                取消
              </NButton>
              <NButton
                round
                type="primary"
                onClick={onEditTitleSubmit}
                loading={forms.editBtnLoading}>
                确定
              </NButton>
            </NSpace>
          </div>
        </NModal>

        <NModal
          v-model:show={forms.preRemoveVisiable}
          preset="card"
          class={['modalTitle', styles.removeVisiable1]}
          title={'删除课件'}>
          <TheMessageDialog
            content={`<p style="text-align: left;">请确认是否删除【${forms.selectItem.name}】，删除后不可恢复</p>`}
            cancelButtonText="取消"
            confirmButtonText="确认"
            loading={forms.messageLoading}
            onClose={() => (forms.preRemoveVisiable = false)}
            onConfirm={() => onRemove()}
          />
        </NModal>

        {/* 应用内预览或上课 */}
        <PreviewWindow
          v-model:show={forms.previewModal}
          type="attend"
          params={forms.previewParams}
        />

        <NModal
          v-model:show={forms.showAttendClass}
          preset="card"
          showIcon={false}
          class={['modalTitle background', styles.attendClassModal]}
          title={'选择班级'}
          blockScroll={false}>
          <AttendClass
            onClose={() => (forms.showAttendClass = false)}
            type={forms.attendClassType}
            onPreview={(item: any) => {
              if (window.matchMedia('(display-mode: standalone)').matches) {
                state.application = window.matchMedia(
                  '(display-mode: standalone)'
                ).matches;
                forms.previewModal = true;
                forms.previewParams = {
                  ...item
                };
              } else {
                const { href } = router.resolve({
                  path: '/attend-class',
                  query: {
                    ...item
                  }
                });
                window.open(href, +new Date() + '');
              }
            }}
            onConfirm={async (item: any) => {
              onStartClass(forms.attendClassItem, item.classGroupId);
            }}
          />
        </NModal>
      </div>
    );
  }
});
