import { defineComponent, onMounted, reactive, 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 { useResizeObserver } from '@vueuse/core';
import {
  api_addByOpenCourseware,
  api_eacherChapterLessonCoursewareRemove,
  api_queryOpenCoursewareByPage,
  api_updateCoursewareInfo,
  teacherChapterLessonCoursewareList
} from '../../../api';
import { useRoute } from 'vue-router';
import TheMessageDialog from '/src/components/TheMessageDialog';
import { eventGlobal } from '/src/utils';

export default defineComponent({
  name: 'courseware-presets',
  emits: ['change'],
  setup(props, { emit }) {
    const prepareStore = usePrepareStore();
    const message = useMessage();
    const route = useRoute();
    const localStorageSubjectId = localStorage.getItem(
      'prepareLessonSubjectId'
    );
    const forms = reactive({
      // 选取参数带的，后取缓存
      messageLoading: false,
      subjectId: route.query.subjectId
        ? Number(route.query.subjectId)
        : localStorageSubjectId
        ? Number(localStorageSubjectId)
        : null,
      courseScheduleSubjectId: route.query.courseScheduleSubjectId,
      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
    });

    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: index !== -1 ? true : false
          });
        });

        forms.openTableList = tempList;
      } catch {
        //
      }
      forms.openLoading = false;
    };

    // 监听选择的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;
        });
      }
    );

    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);
        } else {
          // 判断是否有缓存
          prepareStore.setSubjectId(subjectList[0].id);
        }

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

    onMounted(async () => {
      prepareStore.setClassGroupId(route.query.classGroupId as any);
      // 获取教材分类列表
      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();
        forms.editTitleVisiable = false;
      } catch {
        //
      }
    };

    // 删除
    const onRemove = async () => {
      forms.messageLoading = true;
      try {
        await api_eacherChapterLessonCoursewareRemove({
          id: forms.selectItem.id
        });
        message.success('删除成功');
        getCoursewareList();
        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();
      } catch {
        //
      }
      setTimeout(() => {
        forms.messageLoading = false;
      }, 100);
    };
    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);
                // 保存
              }}
            />
            <NButton
              class={styles.addBtn}
              type="primary"
              onClick={() => {
                eventGlobal.emit('teacher-slideshow', true);
                emit('change', { status: true });
              }}>
              <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}
                        onEditName={() => {
                          forms.selectItem = item;
                          forms.editTitle = item.name;
                          forms.editTitleVisiable = true;
                        }}
                        onDelete={() => {
                          forms.selectItem = item;
                          forms.preRemoveVisiable = true;
                        }}
                      />
                    </div>
                  </div>
                ))}
                {!forms.loading && forms.tableList.length <= 0 && <TheEmpty />}
              </div>
            </NSpin>
          </div>

          <div class={[styles.title, styles.line]}>
            <div class={styles.titleLeft}>
              <i class={[styles.icon, styles.iconCourseware]}></i>
              相关课件
              {forms.openTableList.length > 4 && (
                <span
                  class={styles.more}
                  onClick={() => (forms.showRelatedClass = true)}>
                  查看更多
                  <NIcon>
                    <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>
                </span>
              )}
            </div>

            {forms.openTableList.length > 4 && (
              <NSpace class={styles.swipeControll}>
                <div>
                  <NImage
                    previewDisabled
                    class={[styles.leftIcon]}
                    src={iconSlideRight}
                  />
                </div>
                <div>
                  <NImage previewDisabled src={iconSlideRight} />
                </div>
              </NSpace>
            )}
          </div>

          <NSpin show={forms.openLoading} class={styles.openLoading}>
            <NCarousel
              slidesPerView={4}
              loop={false}
              style={{ width: forms.bodyWidth }}
              v-model:currentIndex={forms.carouselIndex}>
              {forms.openTableList.map((item: any) => (
                <div class={[styles.itemWrap, styles.itemBlock, 'row-nav']}>
                  <div class={styles.itemWrapBox}>
                    <CoursewareType
                      isShowAdd
                      item={item}
                      onAdd={() => onAddCourseware(item)}
                    />
                  </div>
                </div>
              ))}
            </NCarousel>
          </NSpin>
        </NScrollbar>

        <NModal
          v-model:show={forms.showRelatedClass}
          preset="card"
          showIcon={false}
          class={['modalTitle background', styles.attendClassModal]}
          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)}
          />
        </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>
      </div>
    );
  }
});
