import {
  computed,
  defineComponent,
  onMounted,
  reactive,
  ref,
  watch
} from 'vue';
import styles from './index.module.less';
import {
  NButton,
  NTooltip,
  NIcon,
  NImage,
  NModal,
  NScrollbar,
  NSpin,
  NTabPane,
  NTabs,
  useMessage,
  NPopselect,
  NPopover,
  NForm,
  NFormItem,
  NInput,
  NSpace,
  NCascader,
  NSwitch
} 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 iconBlank from '../../../images/icon-blank.png';
import iconPpt from '../../../images/icon-ppt.png';
import CoursewareType from '../../../model/courseware-type';
import TheEmpty from '/src/components/TheEmpty';
import RelatedClass from '../../../model/related-class';
import { modalClickMask, state } from '/src/state';
import { useResizeObserver } from '@vueuse/core';
import AttendClass from '/src/views/prepare-lessons/model/attend-class';
import {
  api_addByOpenCourseware,
  api_teacherChapterLessonCoursewareRemove,
  teacherChapterLessonCoursewareList,
  courseScheduleStart,
  api_courseScheduleCheck
} 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';
import Related from './related';
import Train from '../train';
import ResourceMain from '../../resource-main';
import { useCatchStore } from '/src/store/modules/catchData';
import deepClone from '/src/helpers/deep-clone';
import {
  api_teacherChapterLessonCoursewareAdd,
  api_coursewareToTeacherCourseware,
  api_updateCoursewareInfo
} from '../../../api';
import { vaildPPTUrl } from '/src/utils/urlUtils';
import { useUserStore } from '/src/store/modules/users';
import dayjs from 'dayjs';

export default defineComponent({
  name: 'courseware-presets',
  props: {
    addParam: {
      type: Object,
      default: () => ({})
    }
  },
  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({
      // 选取参数带的，后取缓存
      leftWidth: '100%',
      rightWidth: '0',
      messageLoading: false,
      instrumentId: route.query.instrumentId
        ? Number(route.query.instrumentId)
        : 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,
      openTableShow: true, // 是否显示
      openTableList: [] as any,
      selectItem: {} as any,
      editTitleVisiable: false,
      editTitle: null,
      editBtnLoading: false,
      preRemoveVisiable: false,
      addVisiable: false, // 是否有添加的课件
      carouselIndex: 0,
      showAttendClass: false,
      attendClassType: 'change', //
      attendClassItem: {} as any,
      attendClassId: null as any,
      previewModal: false,
      previewModalType: 'attend' as 'attend' | 'music',
      previewParams: {
        type: '',
        courseId: '',
        instrumentId: '',
        detailId: ''
      } as any,
      workVisiable: false,
      wikiCategoryIdChild: null,
      instrumentErrorVisiable: false,
      instrumentErrorContent: ''
    });

    const getCoursewareList = async () => {
      forms.loading = true;
      try {
        // 判断是否有选择对应的课件 或声部
        if (!prepareStore.getSelectKey) return (forms.loading = false);

        const { data } = await teacherChapterLessonCoursewareList({
          instrumentId: prepareStore.getInstrumentId,
          coursewareDetailKnowledgeId: prepareStore.getSelectKey
        });
        if (!Array.isArray(data)) {
          return;
        }

        const tempList: any = [];
        data.forEach((item: any) => {
          // const firstItem: any =
          //   item.chapterKnowledgeList[0]?.chapterKnowledgeMaterialList[0];

          const firstItem: any =
            item.chapterKnowledgeList[0]?.chapterKnowledgeMaterialList;
          tempList.push({
            id: item.id,
            lessonPreTrainingId: item.lessonPreTrainingId,
            openFlag: item.openFlag,
            openFlagEnable: item.openFlagEnable,
            instrumentNames: item.instrumentNames,
            fromChapterLessonCoursewareId: item.fromChapterLessonCoursewareId,
            name: item.name,
            coverImg: firstItem && firstItem[0]?.bizInfo.coverImg,
            type: firstItem && firstItem[0]?.bizInfo.type,
            isNotWork: item.lessonPreTrainingNum <= 0 ? true : false, // 是否布置作业
            chapterLessonCoursewareTagName: item.chapterLessonCoursewareTagName,
            chapterLessonCoursewareTagColor:
              item.chapterLessonCoursewareTagColor,
            authorName: item.authorName,
            updateTime: item.updateTime
              ? dayjs(item.updateTime).format('YYYY-MM-DD')
              : '',
            coursewareType: item.coursewareType,
            instrumentIds: item.instrumentIds,
            pptId: firstItem && firstItem[0]?.id,
            teacherSaveFlag: item.teacherSaveFlag
          });
        });
        forms.tableList = tempList;
      } catch {
        //
      }
      forms.loading = false;
    };

    // 监听选择的key 左侧选择了其它的课
    let timer: any = null;
    watch(
      () => [prepareStore.getSelectKey, prepareStore.getInstrumentId],
      async () => {
        clearTimeout(timer);
        timer = setTimeout(async () => {
          if (!prepareStore.getInstrumentId) {
            // 获取教材分类列表
            checkInstrumentIds();
          } else {
            getInitInstrumentId();
          }
          eventGlobal.emit('openCoursewareChanged');
          await getCoursewareList();
          subjectRef.value?.syncBarPosition();
        }, 100);
      }
    );

    watch(
      () => prepareStore.getInstrumentList,
      () => {
        checkInstrumentIds();
      }
    );

    const checkInstrumentIds = () => {
      const instrumentsList = prepareStore.getSingleInstrumentList;
      // 并且没有声部时才会更新
      if (instrumentsList.length > 0) {
        // const prepareLessonCourseWareSubjectIsNull = sessionStorage.getItem(
        //   'prepareLessonCourseWareSubjectIsNull'
        // );
        // if (prepareLessonCourseWareSubjectIsNull === 'true') {
        //   prepareStore.setInstrumentId('');
        //   return;
        // }

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

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

        subjectRef.value?.syncBarPosition();
      } else {
        if (forms.instrumentId) {
          prepareStore.setInstrumentId(forms.instrumentId + '');
        }
      }
    };

    const getInitInstrumentId = () => {
      let instrumentId: any = '';
      prepareStore.getInstrumentList.forEach((item: any) => {
        if (Array.isArray(item.instruments)) {
          item.instruments.forEach((child: any) => {
            if (child.id === prepareStore.getInstrumentId) {
              instrumentId = child.id;
            }
          });
        }
      });
      if (instrumentId) {
        forms.wikiCategoryIdChild = instrumentId;
      }
    };
    const subjectRef = ref();
    onMounted(async () => {
      useResizeObserver(
        document.querySelector('#presetsLeftRef') as HTMLElement,
        (entries: any) => {
          const entry = entries[0];
          const { width } = entry.contentRect;
          forms.leftWidth = width + 'px';
        }
      );
      useResizeObserver(
        document.querySelector('#presetsRightRef') as HTMLElement,
        (entries: any) => {
          const entry = entries[0];
          const { width } = entry.contentRect;
          forms.rightWidth = width + 'px';
        }
      );

      prepareStore.setClassGroupId(route.query.classGroupId as any);
      if (!prepareStore.getInstrumentId) {
        // 获取教材分类列表
        checkInstrumentIds();
      } else {
        getInitInstrumentId();
      }

      await getCoursewareList();

      if (props.addParam.isAdd) {
        forms.addVisiable = true;
      }
    });

    // 删除
    const onRemove = async () => {
      forms.messageLoading = true;
      try {
        await api_teacherChapterLessonCoursewareRemove({
          id: forms.selectItem.id
        });
        message.success('删除成功');
        getCoursewareList();
        // getOpenCoursewareList();
        eventGlobal.emit('openCoursewareChanged');
        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();
        eventGlobal.emit('openCoursewareChanged');
      } 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.previewModalType = 'attend';
        forms.previewParams = {
          type: 'preview',
          courseId: id,
          instrumentId: prepareStore.getInstrumentId,
          detailId: prepareStore.getSelectKey,
          lessonCourseId: prepareStore.getBaseCourseware.id
        };
      } else {
        const { href } = router.resolve({
          path: '/attend-class',
          query: {
            type: 'preview',
            courseId: id,
            instrumentId: prepareStore.getInstrumentId,
            detailId: prepareStore.getSelectKey,
            lessonCourseId: prepareStore.getBaseCourseware.id
          }
        });
        window.open(href, +new Date() + '');
      }
    };

    const onStartClass = async (
      item: any,
      classGroupId: any,
      instrumentId?: any
    ) => {
      if (classGroupId) {
        // 开始上课
        const res = await courseScheduleStart({
          lessonCoursewareKnowledgeDetailId: prepareStore.selectKey,
          classGroupId: classGroupId,
          useChapterLessonCoursewareId: item.id
          // instrumentId: prepareStore.getInstrumentId
        });
        if (window.matchMedia('(display-mode: standalone)').matches) {
          state.application = window.matchMedia(
            '(display-mode: standalone)'
          ).matches;
          forms.previewModal = true;
          forms.previewModalType = 'attend';
          fscreen();
          forms.previewParams = {
            type: 'class',
            classGroupId: classGroupId,
            courseId: item.id,
            instrumentId: prepareStore.getInstrumentId, // 产品说预览和上课都取当前选中的乐器
            // instrumentId: instrumentId || route.query.instrumentId,
            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,
              instrumentId: prepareStore.getInstrumentId,
              // instrumentId: instrumentId || route.query.instrumentId,
              detailId: prepareStore.getSelectKey,
              classId: res.data,
              lessonCourseId: prepareStore.getBaseCourseware.id,
              preStudentNum: forms.preStudentNum
            }
          });
          window.open(href, +new Date() + '');
        }

        forms.showAttendClass = false;
        forms.instrumentErrorVisiable = false;
      } else {
        forms.showAttendClass = true;
        forms.attendClassType = 'change';
        forms.attendClassItem = item;
      }
    };

    /** 上课前检测声部 */
    const onClassCheckInstrument = async (
      item: any,
      classGroupId: any,
      instrumentId?: any
    ) => {
      try {
        if (classGroupId) {
          const { data } = await api_courseScheduleCheck({
            classGroupId,
            chapterLessonCoursewareId: item.id
          });
          forms.attendClassItem = item;
          forms.attendClassId = classGroupId;
          if (!data.chapterLessonCoursewareFlag) {
            forms.instrumentErrorVisiable = true;
            forms.instrumentErrorContent =
              '课件支持的乐器与班级不符，是否继续使用该课件上课？';
          } else if (!data.materialFlag) {
            forms.instrumentErrorVisiable = true;
            forms.instrumentErrorContent =
              '课件中含有不符合班级乐器的资源，是否继续使用该课件上课？';
          } else {
            onStartClass(item, classGroupId, instrumentId);
          }
        } else {
          onStartClass(item, classGroupId, instrumentId);
        }
      } catch {
        //
      }
    };

    const selectChildObj = (item: any) => {
      const obj: any = {};
      item?.forEach((child: any) => {
        if (child.id === forms.wikiCategoryIdChild) {
          obj.selected = true;
          obj.name = child.name;
          obj.label = child.name;
        }
      });
      return obj;
    };

    const tabInstrumentValue = computed(() => {
      let instrumentId: any = prepareStore.getInstrumentId
        ? prepareStore.getInstrumentId
        : '';
      prepareStore.getFormatInstrumentList.forEach((item: any) => {
        if (Array.isArray(item.instruments)) {
          item.instruments.forEach((child: any) => {
            if (child.id === prepareStore.getInstrumentId) {
              instrumentId = item.id + '';
            }
          });
        }
      });
      return instrumentId;
    });
    /* ppt课件 */
    const userStore = useUserStore();
    const pptCourseware = reactive({
      pptCoursewareShow: false,
      id: '',
      name: '',
      subjects: [],
      openFlagEnable: true,
      openFlag: false
    });
    const pptFormsRef = ref();
    const subjectList = ref<any[]>([]);
    const updateSubjectList = (ids?: any[]) => {
      // 获取适用乐器编号 ，修改的乐器编号，集合
      ids = ids || [];
      const courseIds: any = [];
      prepareStore.getInstrumentList.forEach((item: any) => {
        if (Array.isArray(item.instruments)) {
          item.instruments.forEach((child: any) => {
            courseIds.push(child.id);
          });
        }
      });
      const allIds = [...new Set([...courseIds, ...ids])];

      const tempList: any = [];
      useCatchStore().getSubjectList.forEach((item: any) => {
        const temp = deepClone(item);
        temp.enableFlag = false;
        if (Array.isArray(temp.instruments)) {
          temp.instruments.forEach((child: any) => {
            child.enableFlag = false;
            if (allIds.includes(child.id)) {
              child.enableFlag = true;
              temp.enableFlag = true;
            }
          });
        }
        tempList.push(temp);
      });
      const tempSubjects: any[] = [];
      tempList.forEach((subject: any) => {
        if (subject.enableFlag) {
          const { instruments, ...r } = subject;

          if (instruments && instruments.length > 0) {
            const tempChild: any[] = [];
            instruments?.forEach((instrument: any) => {
              if (instrument.enableFlag) {
                tempChild.push(instrument);
              }
            });

            if (tempChild.length > 0)
              tempSubjects.push({ ...r, instruments: tempChild });
          }
        }
      });
      subjectList.value = tempSubjects;
    };
    const chioseAll = (list: any) => {
      // 全选
      const ids = [] as any;
      list.map((item: any) => {
        if (Array.isArray(item.instruments)) {
          item.instruments.forEach((c: any) => {
            ids.push(c.value);
          });
        }
      }) as any;
      pptCourseware.subjects = ids;
    };
    function handlePptConfirm() {
      pptFormsRef.value?.validate(async (err: any) => {
        if (err) {
          return;
        }
        const { id, name, subjects, openFlag, openFlagEnable } = pptCourseware;
        if (id) {
          const params = {
            id,
            name,
            instrumentIds: subjects.join(','),
            openFlag,
            autoPlay: false,
            openFlagEnable
          };
          api_updateCoursewareInfo(params).then(res => {
            if (res.code === 200) {
              pptCourseware.pptCoursewareShow = false;
              getCoursewareList();
              eventGlobal.emit('openCoursewareChanged');
            }
          });
        } else {
          const params = {
            name,
            instrumentIds: subjects.join(','),
            openFlag,
            autoPlay: false,
            coursewareDetailKnowledgeId: prepareStore.getSelectKey,
            coursewareType: 'PPT'
          };
          api_teacherChapterLessonCoursewareAdd(params).then(res => {
            if (res.code === 200) {
              pptCourseware.pptCoursewareShow = false;
              getCoursewareList();
              eventGlobal.emit('openCoursewareChanged');
              const { teacherSaveFlag, id, chapterKnowledgeList } = res.data;
              const instrumentIdTab = prepareStore.getInstrumentId;
              handleRouterPPT(
                {
                  teacherSaveFlag,
                  id,
                  pptId:
                    chapterKnowledgeList[0]?.chapterKnowledgeMaterialList[0]?.id
                },
                pptCourseware.subjects.includes(instrumentIdTab)
                  ? instrumentIdTab
                  : pptCourseware.subjects[0]
              );
            }
          });
        }
      });
    }
    function handlePptEdit(item: Record<string, any>) {
      updateSubjectList();
      pptCourseware.id = item.id;
      pptCourseware.name = item.name;
      pptCourseware.subjects = item.instrumentIds
        ? item.instrumentIds.split(',')
        : [];
      pptCourseware.openFlag = item.openFlag;
      pptCourseware.openFlagEnable = item.openFlagEnable;
      pptCourseware.pptCoursewareShow = true;
    }
    async function handleRouterPPT(
      item: Record<string, any>,
      instrumentId: string
    ) {
      const teacherSaveFlag = item.teacherSaveFlag;
      // 当teacherSaveFlag为false时候，需要把平台数据转为老师自己的课件
      if (!teacherSaveFlag) {
        const dataRes = await api_coursewareToTeacherCourseware(item.id);
        item.teacherSaveFlag = true;
        // 这里需要拿最新的id
        item.pptId =
          dataRes.data.chapterKnowledgeList[0].chapterKnowledgeMaterialList[0].id;
      }

      const href = `${vaildPPTUrl()}/#/pptEditor?id=${
        item.pptId
      }&Authorization=${
        userStore.getToken
      }&instrumentId=${instrumentId}&lessonCoursewareKnowledgeId=${
        prepareStore.getSelectKey
      }&fromType=TEACHER&pptResourcesType=TEACHER`;
      if (window.matchMedia('(display-mode: standalone)').matches) {
        forms.previewModal = true;
        forms.previewModalType = 'music';
        // window.open(href);
        forms.previewParams = {
          src: href
        };
      } else {
        window.open(href);
      }

      // 刷新一下列表
      !teacherSaveFlag && getCoursewareList();
    }
    onMounted(async () => {
      await useCatchStore().getSubjects();
    });
    return () => (
      <div
        class={[
          styles.coursewarePresetsContainer,
          forms.openTableShow && styles.rightLineShow
        ]}>
        <div
          class={styles.presetsLeft}
          id="presetsLeftRef"
          style={{ width: `calc(${forms.leftWidth} - ${forms.rightWidth})` }}>
          <NTabs
            ref={subjectRef}
            defaultValue=""
            paneClass={styles.paneTitle}
            justifyContent="start"
            paneWrapperClass={styles.paneWrapperContainer}
            value={tabInstrumentValue.value}
            onUpdate:value={(val: any) => {
              prepareStore.getFormatInstrumentList.forEach((item: any) => {
                if (item.value.toString() === val.toString()) {
                  prepareStore.setInstrumentId(val);
                  // 保存
                  forms.instrumentId = val;
                  forms.wikiCategoryIdChild = null;
                }
              });

              // if (!val) {
              //   prepareStore.setInstrumentId(val);
              //   // 保存
              //   forms.instrumentId = val;
              //   forms.wikiCategoryIdChild = null;
              //   sessionStorage.setItem(
              //     'prepareLessonCourseWareSubjectIsNull',
              //     val ? 'false' : 'true'
              //   );
              // }
            }}
            v-slots={{
              suffix: () => (
                <NPopover
                  placement="bottom"
                  trigger="hover"
                  showArrow={false}
                  to={false}
                  duration={50}>
                  {{
                    trigger: () => (
                      <NButton
                        class={styles.addBtn}
                        type="primary"
                        bordered={false}>
                        <NImage
                          class={styles.addBtnIcon}
                          previewDisabled
                          src={add}></NImage>
                        创建课件
                      </NButton>
                    ),
                    default: () => (
                      <div>
                        <div
                          class={styles.popoverItem}
                          onClick={() => {
                            eventGlobal.emit('teacher-slideshow', true);
                            emit('change', {
                              status: true,
                              type: 'create'
                            });
                          }}>
                          <span>
                            <img src={iconBlank} />
                            空白课件
                          </span>
                        </div>
                        <div
                          class={styles.popoverItem}
                          onClick={() => {
                            updateSubjectList();
                            Object.assign(pptCourseware, {
                              pptCoursewareShow: true,
                              id: '',
                              name: '',
                              subjects: [],
                              openFlagEnable: true,
                              openFlag: false
                            });
                          }}>
                          <span>
                            <img src={iconPpt} />
                            演示文稿(PPT)
                          </span>
                        </div>
                      </div>
                    )
                  }}
                </NPopover>
              )
            }}>
            {[
              // { name: '全部乐器', id: '', label: '全部乐器', value: '' },
              ...prepareStore.getFormatInstrumentList
            ].map((item: any, index: number) => (
              <NTabPane
                name={`${item.value}`}
                tab={item.label}
                disabled={item.instruments?.length > 0}
                displayDirective="if">
                {{
                  tab: () =>
                    item.instruments?.length > 0 ? (
                      <NPopselect
                        options={item.instruments}
                        trigger="hover"
                        v-model:value={forms.wikiCategoryIdChild}
                        onUpdate:value={(val: any) => {
                          // onSearch();
                          prepareStore.setInstrumentId(val);
                          // 保存
                          forms.instrumentId = val;

                          // if (!val) {
                          //   sessionStorage.setItem(
                          //     'prepareLessonCourseWareSubjectIsNull',
                          //     val ? 'false' : 'true'
                          //   );
                          // }
                        }}
                        key={item.id}
                        class={styles.popSelect}>
                        <span
                          class={[
                            styles.textBtn,
                            selectChildObj(item.instruments).selected &&
                              styles.textBtnActive
                          ]}>
                          {selectChildObj(item.instruments).label || item.label}
                          <i class={styles.iconArrow}></i>
                        </span>
                      </NPopselect>
                    ) : (
                      item.label
                    )
                }}
              </NTabPane>
            ))}
          </NTabs>
          <NSpin show={forms.loading}>
            <NScrollbar class={styles.coursewarePresets}>
              <div style={{ overflow: 'hidden' }}>
                <div
                  class={[
                    styles.list,
                    !forms.loading &&
                      forms.tableList.length <= 0 &&
                      styles.listEmpty
                  ]}>
                  {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={type => {
                            //
                            if (item.coursewareType === 'PPT') {
                              if (type === 'PPT') {
                                // 进入 ppt 编辑页面
                                handleRouterPPT(
                                  item,
                                  prepareStore.getInstrumentId as any
                                );
                              } else {
                                handlePptEdit(item);
                              }
                            } else {
                              eventGlobal.emit('teacher-slideshow', true);
                              emit('change', {
                                status: true,
                                type: 'update',
                                groupItem: { id: item.id }
                              });
                            }
                          }}
                          onStartClass={() =>
                            onClassCheckInstrument(item, forms.classGroupId)
                          }
                          onDelete={() => {
                            forms.selectItem = item;
                            forms.preRemoveVisiable = true;
                          }}
                          // 布置作业
                          onWork={() => {
                            forms.workVisiable = true;
                            forms.selectItem = item;
                          }}
                        />
                      </div>
                    </div>
                  ))}
                  {!forms.loading && forms.tableList.length <= 0 && (
                    <TheEmpty
                      class={styles.empty1}
                      description="当前章节暂无课件，快点击右上角创建课件吧"
                    />
                  )}
                </div>
              </div>
            </NScrollbar>
          </NSpin>
        </div>

        <div class={styles.presetsRight} id="presetsRightRef">
          <NTooltip
            showArrow={false}
            show={false}
            animated={false}
            duration={0}
            delay={0}>
            {{
              trigger: () => (
                <div
                  class={[
                    styles.presetsArrar,
                    !forms.openTableShow && styles.presetsArrarActive
                  ]}
                  onClick={() => (forms.openTableShow = !forms.openTableShow)}>
                  <NIcon>
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
                      <path
                        d="M16.62 2.99a1.25 1.25 0 0 0-1.77 0L6.54 11.3a.996.996 0 0 0 0 1.41l8.31 8.31c.49.49 1.28.49 1.77 0s.49-1.28 0-1.77L9.38 12l7.25-7.25c.48-.48.48-1.28-.01-1.76z"
                        fill="currentColor"></path>
                    </svg>
                  </NIcon>
                </div>
              ),
              default: () => <div>{forms.openTableShow ? '收起' : '展开'}</div>
            }}
          </NTooltip>

          <Related
            onMore={() => (forms.showRelatedClass = true)}
            onAdd={(item: any) => {
              onAddCourseware(item);
            }}
            onLook={(item: any) => {
              onPreviewAttend(item.id);
            }}
          />
        </div>
        {/* )} */}

        <NModal
          maskClosable={modalClickMask}
          v-model:show={forms.showRelatedClass}
          preset="card"
          showIcon={false}
          class={['modalTitle background', styles.attendClassModal1]}
          title={'相关课件'}
          blockScroll={false}>
          <RelatedClass
            tableList={forms.tableList}
            instrumentList={prepareStore.getInstrumentList}
            instrumentId={prepareStore.getInstrumentId 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
          maskClosable={modalClickMask}
          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>

        <NModal
          maskClosable={modalClickMask}
          v-model:show={forms.addVisiable}
          preset="card"
          class={['modalTitle', styles.removeVisiable1]}
          title={'保存成功'}>
          <TheMessageDialog
            content={`<p style="text-align: left;">【${props.addParam.name}】暂未设置课件作业，是否现在去设置课件作业</p>`}
            cancelButtonText="稍后设置"
            confirmButtonText="立即设置"
            // loading={forms.messageLoading}
            onClose={() => (forms.addVisiable = false)}
            onConfirm={() => {
              forms.addVisiable = false;
              forms.workVisiable = true;
              forms.selectItem = {
                id: props.addParam.id,
                name: props.addParam.name
              };
            }}
          />
        </NModal>

        <NModal
          maskClosable={modalClickMask}
          v-model:show={forms.instrumentErrorVisiable}
          preset="card"
          class={['modalTitle', styles.removeVisiable1]}
          title={'温馨提示'}>
          <TheMessageDialog
            content={forms.instrumentErrorContent}
            contentDirection="left"
            onClose={() => {
              forms.instrumentErrorVisiable = false;
            }}
            onConfirm={() => {
              //
              onStartClass(forms.attendClassItem, forms.attendClassId);
            }}
          />
        </NModal>

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

        <NModal
          maskClosable={modalClickMask}
          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.previewModalType = 'attend';
                forms.previewParams = {
                  ...item
                };
              } else {
                const { href } = router.resolve({
                  path: '/attend-class',
                  query: {
                    ...item
                  }
                });
                window.open(href, +new Date() + '');
              }
            }}
            onConfirm={async (item: any) => {
              onClassCheckInstrument(
                forms.attendClassItem,
                item.classGroupId,
                item.instrumentId
              );
            }}
          />
        </NModal>

        <NModal
          maskClosable={modalClickMask}
          v-model:show={forms.workVisiable}
          preset="card"
          class={['modalTitle background', styles.workVisiable]}
          title={
            forms.selectItem.lessonPreTrainingId ? '编辑作业' : '创建作业'
          }>
          <div id="model-homework-height" class={styles.workContainer}>
            <div class={styles.workTrain}>
              <Train
                cardType="prepare"
                lessonPreTraining={{
                  title: forms.selectItem.name + '-课后作业',
                  chapterId: forms.selectItem.id, // 课件编号
                  id: forms.selectItem.lessonPreTrainingId // 作业编号
                }}
                onChange={(val: any) => {
                  forms.workVisiable = val.status;
                  getCoursewareList();
                }}
              />
            </div>
            <div class={styles.resourceMain}>
              <ResourceMain cardType="prepare" />
            </div>
          </div>
        </NModal>
        {/* 新建ppt课件 */}
        <NModal
          maskClosable={modalClickMask}
          v-model:show={pptCourseware.pptCoursewareShow}
          preset="card"
          class={['modalTitle', styles.pptCoursewareModal]}
          title={'课件设置'}>
          <NForm
            ref={pptFormsRef}
            model={pptCourseware}
            labelAlign="right"
            labelPlacement="left">
            <NFormItem
              label="课件名称"
              path="name"
              rule={[
                {
                  required: true,
                  message: '请输入课件名称',
                  trigger: ['blur', 'change']
                }
              ]}>
              <NInput
                placeholder="请输入课件名称"
                v-model:value={pptCourseware.name}
                maxlength={20}
                clearable
              />
            </NFormItem>
            <NFormItem
              label="适用乐器"
              path="subjects"
              rule={[
                {
                  required: true,
                  message: '请选择适用乐器',
                  trigger: ['blur', 'change'],
                  type: 'array'
                }
              ]}>
              <NCascader
                placeholder="请选择乐器（可多选）"
                class={styles.btnSubjectList}
                options={subjectList.value}
                checkStrategy="child"
                showPath={false}
                childrenField="instruments"
                expandTrigger="hover"
                labelField="name"
                valueField="id"
                clearable
                filterable
                multiple
                maxTagCount={1}
                v-model:value={pptCourseware.subjects}
                v-slots={{
                  action: () => (
                    <NButton
                      text
                      style=" --n-width: 100% "
                      size="small"
                      onClick={() => chioseAll(subjectList.value)}>
                      全选
                    </NButton>
                  )
                }}
              />
            </NFormItem>
            <div class={styles.btnItem}>
              <span class={styles.btnTitle}>
                公开课件
                <NTooltip style={{ maxWidth: '200px' }} showArrow={false}>
                  {{
                    trigger: () => <i class={styles.iconQuestion}></i>,
                    default: () => '公开课件后，其它老师可以使用该课件上课'
                  }}
                </NTooltip>
              </span>
              {!pptCourseware.openFlagEnable ? (
                <NTooltip style={{ maxWidth: '200px' }} showArrow={false}>
                  {{
                    trigger: () => (
                      <NSwitch
                        size="large"
                        v-model:value={pptCourseware.openFlag}
                        disabled={!pptCourseware.openFlagEnable}
                      />
                    ),
                    default: () =>
                      '为尊重课件原作者，在“相关课件”中添加的课件不支持公开'
                  }}
                </NTooltip>
              ) : (
                <NSwitch
                  size="large"
                  v-model:value={pptCourseware.openFlag}
                  disabled={!pptCourseware.openFlagEnable}
                />
              )}
            </div>
            <NSpace class={styles.updateBtnGroup}>
              <NButton
                strong
                type="default"
                round
                onClick={() => {
                  pptCourseware.pptCoursewareShow = false;
                }}>
                取消
              </NButton>
              <NButton strong type="primary" round onClick={handlePptConfirm}>
                确认
              </NButton>
            </NSpace>
          </NForm>
        </NModal>
      </div>
    );
  }
});
