import { defineComponent, onMounted, reactive, watch } from 'vue';
import styles from './index.module.less';
import {
  NButton,
  NModal,
  NScrollbar,
  NSelect,
  NSpace,
  NSpin,
  useMessage,
  useDialog
} from 'naive-ui';
import CardType from '/src/components/card-type';
import AttendClass from '/src/views/prepare-lessons/model/attend-class';
import { usePrepareStore } from '/src/store/modules/prepareLessons';
import { useCatchStore } from '/src/store/modules/catchData';
import TheEmpty from '/src/components/TheEmpty';
import {
  courseScheduleStart,
  queryCourseware,
  saveCourseware,
  teacherKnowledgeMaterialDelete
} from '../../../api';
import Draggable from 'vuedraggable';
import iconDelete from '../../../images/icon-delete.png';
import { onBeforeRouteUpdate, useRoute, useRouter } from 'vue-router';
import deepClone from '/src/helpers/deep-clone';
import CardPreview from '/src/components/card-preview';
import PreviewWindow from '/src/views/preview-window';
import { state } from '/src/state';
import SubjectSync from '../../../model/subject-sync';
import { eventGlobal } from '/src/utils';

export default defineComponent({
  name: 'courseware-modal',
  setup() {
    const catchStore = useCatchStore();
    const prepareStore = usePrepareStore();
    const route = useRoute();
    const router = useRouter();
    const dialog = useDialog();
    const message = useMessage();
    const forms = reactive({
      className: route.query.name as any,
      classGroupId: route.query.classGroupId,
      subjectId: route.query.subjectId ? Number(route.query.subjectId) : null,
      coursewareList: [] as any,
      loadingStatus: false,
      showAttendClass: false,
      attendClassType: 'select', //
      removeIds: [] as any, // 临时删除的编号
      drag: false,
      isEdit: false, // 是否更新数据
      editSubjectIds: '', // 声部编号
      removeVisiable: false,
      removeVisiable1: false,
      subjectSyncVisiable: false, // 同步声部
      show: false,
      item: {} as any,
      previewModal: false,
      previewParams: {
        type: '',
        subjectId: '',
        detailId: ''
      } as any
    });

    // 获取列表
    const getList = async () => {
      forms.loadingStatus = true;
      try {
        // 判断是否有选择对应的课件 或声部
        if (!prepareStore.getSelectKey || !prepareStore.getSubjectId)
          return (forms.loadingStatus = false);
        const { data } = await queryCourseware({
          coursewareDetailKnowledgeId: prepareStore.getSelectKey,
          subjectId: prepareStore.getSubjectId,
          page: 1,
          rows: 99
        });
        const tempRows = data.rows || [];
        const temp: any = [];
        tempRows.forEach((row: any) => {
          temp.push({
            id: row.id,
            materialId: row.materialId,
            coverImg: row.coverImg,
            type: row.materialType,
            title: row.materialName,
            isCollect: !!row.favoriteFlag,
            isSelected: row.source === 'PLATFORM' ? true : false,
            content: row.content,
            removeFlag: row.removeFlag
          });
        });

        prepareStore.setCoursewareList(temp || []);

        const tempCourse: any = [];
        temp.forEach((item: any) => {
          if (!forms.removeIds.includes(item.id)) {
            tempCourse.push(item);
          }
        });
        forms.coursewareList = tempCourse;
      } catch {
        //
      }
      forms.loadingStatus = false;
    };

    // 监听选择的key 左侧选择了其它的课
    watch(
      () => prepareStore.getSelectKey,
      () => {
        forms.drag = false;
        getList();
      }
    );
    // 声部变化时
    watch(
      () => prepareStore.getSubjectId,
      () => {
        getList();
      }
    );
    watch(
      () => prepareStore.getIsAddResource,
      (val: boolean) => {
        if (val) {
          getList();
          prepareStore.setIsAddResource(false);
        }
      }
    );

    // 删除
    const onDelete = (item: any) => {
      //
      forms.removeIds.push(item.id);
      const index = forms.coursewareList.findIndex(
        (c: any) => c.id === item.id
      );
      forms.coursewareList.splice(index, 1);
      forms.isEdit = true;
      // prepareStore.setCoursewareList(forms.coursewareList);
      // console.log(prepareStore.getCoursewareList, 'getCourseware');
    };

    // 完成编辑
    const onOverEdit = async () => {
      try {
        const temp: any = [];
        forms.coursewareList.forEach((item: any) => {
          temp.push({
            materialName: item.title,
            materialType: item.type,
            materialId: item.materialId,
            id: item.id
          });
        });
        // 保存课件
        // 判断是否编辑，如果编辑则取选择的声部
        await saveCourseware({
          coursewareDetailKnowledgeId: prepareStore.getSelectKey,
          lessonCoursewareId: prepareStore.getLessonCoursewareId,
          lessonCoursewareDetailId: prepareStore.getLessonCoursewareDetailId,
          subjectId: forms.isEdit
            ? forms.editSubjectIds
            : prepareStore.getSubjectId,
          materialList: [...temp]
        });

        forms.drag = false;
        message.success('编辑成功');
        forms.removeVisiable = false;
        prepareStore.setIsEditResource(false);
        // 重置临时删除编号
        forms.removeIds = [];
        await getList();
      } catch {
        //
      }
    };

    // 预览上课
    const onPreviewAttend = () => {
      // 获取上架的数据
      let count = 0;
      forms.coursewareList.forEach((item: any) => {
        if (!item.removeFlag) {
          count++;
        }
      });
      if (count <= 0) {
        message.error('课件不能为空');
        return;
      }
      // 判断是否在应用里面
      if (window.matchMedia('(display-mode: standalone)').matches) {
        state.application = window.matchMedia(
          '(display-mode: standalone)'
        ).matches;
        forms.previewModal = true;
        fscreen();
        forms.previewParams = {
          type: 'preview',
          subjectId: prepareStore.getSubjectId,
          detailId: prepareStore.getSelectKey,
          lessonCourseId: prepareStore.getBaseCourseware.id
        };
      } else {
        const { href } = router.resolve({
          path: '/attend-class',
          query: {
            type: 'preview',
            subjectId: prepareStore.getSubjectId,
            detailId: prepareStore.getSelectKey,
            lessonCourseId: prepareStore.getBaseCourseware.id
          }
        });
        window.open(href, +new Date() + '');
      }
    };
    const fscreen = () => {
      const el = document.documentElement;
      const isFullscreen =
        document.fullScreen ||
        document.mozFullScreen ||
        document.webkitIsFullScreen;
      if (!isFullscreen) {
        //进入全屏
        (el.requestFullscreen && el.requestFullscreen()) ||
          (el.mozRequestFullScreen && el.mozRequestFullScreen()) ||
          (el.webkitRequestFullscreen && el.webkitRequestFullscreen()) ||
          (el.msRequestFullscreen && el.msRequestFullscreen());
      }
    };
    // 单个删除
    const onRemove = async (item: any) => {
      try {
        dialog.warning({
          title: '提示',
          content: '该资源已下架，是否删除？',
          positiveText: '确定',
          negativeText: '取消',
          onPositiveClick: async () => {
            forms.removeIds.push(item.id);
            await teacherKnowledgeMaterialDelete({ ids: item.id });
            message.success('删除成功');
            getList();
          }
        });
      } catch {
        //
      }
    };

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

    const checkSubjectIds = () => {
      const subjectList = prepareStore.getSubjectList;
      // console.log(subjectList, 'subjectList');
      // 并且没有声部时才会更新
      if (subjectList.length > 0) {
        // 判断浏览器上面是否有
        const index = subjectList.findIndex(
          (subject: any) => subject.id == forms.subjectId
        );
        // 并且声部在列表中
        if (forms.subjectId && index >= 0) {
          prepareStore.setSubjectId(forms.subjectId);
        } else if (!prepareStore.getSubjectId) {
          // 判断是否有缓存
          prepareStore.setSubjectId(subjectList[0].id);
        }
      }
    };

    watch(
      () => route.query,
      async () => {
        forms.className = route.query.name as any;
        forms.classGroupId = route.query.classGroupId as any;
        forms.subjectId = route.query.subjectId
          ? Number(route.query.subjectId)
          : null;

        checkSubjectIds();
        await getList();
      }
    );

    onMounted(async () => {
      // 获取教材分类列表
      checkSubjectIds();

      await getList();

      // 动态添加数据
      eventGlobal.on('onPrepareAddItem', (item: any) => {
        forms.coursewareList.push(item);
        prepareStore.setCoursewareList(forms.coursewareList);

        forms.isEdit = true;
      });
    });

    return () => (
      <div class={styles.coursewareModal}>
        <div class={styles.btnGroup}>
          {forms.drag ? (
            <NSpace>
              <NButton
                type="default"
                onClick={() => {
                  if (forms.isEdit) {
                    forms.subjectSyncVisiable = true;
                  } else {
                    forms.removeVisiable = true;
                  }
                }}>
                完成编辑
              </NButton>
              <NButton
                type="error"
                onClick={() => {
                  forms.drag = false;
                  forms.isEdit = false;
                  prepareStore.setIsEditResource(false);
                  forms.removeIds = [];
                  getList();
                }}>
                取消编辑
              </NButton>
              <NButton
                type="error"
                onClick={() => {
                  forms.removeVisiable1 = true;
                  forms.isEdit = true;
                }}>
                清空资源
              </NButton>
              <span class={styles.tips}>拖动可将资源进行排序</span>
            </NSpace>
          ) : (
            <NSpace>
              {forms.classGroupId && (
                <div class={styles.btnItem}>
                  <span class={styles.btnTitle}>上课班级：</span>
                  <div
                    onClick={() => {
                      forms.showAttendClass = true;
                      forms.attendClassType = 'change';
                    }}>
                    <NSelect
                      placeholder="选择声部"
                      labelField="name"
                      valueField="id"
                      class={styles.btnClassList}
                      value={forms.className}
                      disabled
                    />
                  </div>
                </div>
              )}

              <div class={styles.btnItem}>
                <span class={styles.btnTitle}>声部：</span>
                <NSelect
                  placeholder="选择声部"
                  class={styles.btnSubjectList}
                  options={prepareStore.getSubjectList}
                  labelField="name"
                  valueField="id"
                  value={prepareStore.getSubjectId}
                  onUpdate:value={(val: any) => {
                    prepareStore.setSubjectId(val);
                    getList();
                  }}
                />
              </div>
            </NSpace>
          )}

          {/* 编辑 */}
          {!forms.drag && (
            <NSpace>
              <NButton
                type="default"
                onClick={() => {
                  forms.drag = true;
                  prepareStore.setIsEditResource(true);

                  // forms.subjectSyncVisiable = true;
                }}>
                编辑
              </NButton>
            </NSpace>
          )}
        </div>

        <NScrollbar class={styles.listContainer} {...{ id: 'lessons-2' }}>
          <NSpin show={forms.loadingStatus}>
            <div
              class={[
                styles.listSection,
                !forms.loadingStatus && forms.coursewareList.length <= 0
                  ? styles.emptySection
                  : ''
              ]}>
              {forms.coursewareList.length > 0 && (
                <>
                  {forms.drag ? (
                    <Draggable
                      v-model:modelValue={forms.coursewareList}
                      itemKey="id"
                      componentData={{
                        itemKey: 'id',
                        tag: 'div',
                        animation: 200,
                        group: 'description',
                        disabled: false
                      }}
                      class={styles.list}>
                      {{
                        item: (element: any) => {
                          const item = element.element;
                          return (
                            <div
                              data-id={item.id}
                              class={[styles.itemBlock, 'row-nav']}>
                              <CardType
                                class={[styles.itemContent]}
                                isShowCollect={false}
                                offShelf={item.removeFlag ? true : false}
                                onOffShelf={() => onRemove(item)}
                                item={item}
                              />
                              <div class={styles.itemOperation}>
                                <img
                                  src={iconDelete}
                                  class={styles.iconDelete}
                                  onClick={(e: MouseEvent) => {
                                    e.stopPropagation();
                                    onDelete(item);
                                  }}
                                />
                              </div>
                            </div>
                          );
                        }
                      }}
                    </Draggable>
                  ) : (
                    <div class={styles.list}>
                      {forms.coursewareList.map((item: any) => (
                        <CardType
                          class={[styles.itemContent, 'handle']}
                          isShowCollect={false}
                          item={item}
                          offShelf={item.removeFlag ? true : false}
                          onOffShelf={() => onRemove(item)}
                          disabledMouseHover={false}
                          onClick={() => {
                            if (item.type === 'IMG') return;
                            forms.show = true;
                            forms.item = item;
                          }}
                        />
                      ))}
                    </div>
                  )}
                </>
              )}

              {!forms.loadingStatus && forms.coursewareList.length <= 0 && (
                <TheEmpty description="暂无课件" />
              )}
            </div>
          </NSpin>
        </NScrollbar>

        <div class={styles.btnGroup} style={{ justifyContent: 'flex-end' }}>
          <NSpace justify="end">
            <NButton type="primary" onClick={onPreviewAttend}>
              预览课件
            </NButton>
            <NButton
              {...{ id: 'lessons-3' }}
              type="primary"
              class={styles.btnClassStart}
              onClick={async () => {
                let count = 0;
                forms.coursewareList.forEach((item: any) => {
                  if (!item.removeFlag) {
                    count++;
                  }
                });
                if (count <= 0) {
                  message.error('课件不能为空');
                  return;
                }

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

        <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={(item: any) => {
              console.log(item, 'confirm');
              forms.className = item.name;
              forms.classGroupId = item.classGroupId;
              forms.subjectId = item.subjectId;
              forms.showAttendClass = false;

              checkSubjectIds();
              // 声部切换时
              eventGlobal.emit('onChangeClass', {
                lastUseCoursewareId: item.lastUseCoursewareId,
                unit: item.unit
              });
            }}
          />
        </NModal>

        {/* 弹窗查看 */}
        <CardPreview v-model:show={forms.show} item={forms.item} />

        <NModal
          v-model:show={forms.removeVisiable}
          preset="card"
          class={['modalTitle', styles.removeVisiable]}
          title={'提示'}>
          <div class={styles.studentRemove}>
            <p>是否完成编辑？</p>

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

        <NModal
          v-model:show={forms.removeVisiable1}
          preset="card"
          class={['modalTitle', styles.removeVisiable1]}
          title={'清空资源'}>
          <div class={styles.studentRemove}>
            <p>
              请确认是否要清空资源？
              <span>点击确认后所有的素材内容 将被清空掉。</span>
            </p>

            <NSpace class={styles.btnGroupModal} justify="center">
              <NButton
                round
                type="primary"
                onClick={() => {
                  forms.coursewareList.forEach((item: any) => {
                    forms.removeIds.push(item.id);
                  });
                  forms.coursewareList = [];
                  forms.removeVisiable1 = false;
                  // prepareStore.setCoursewareList([]);

                  console.log(prepareStore.getCoursewareList, 'getCourseware1');
                }}>
                确定
              </NButton>
              <NButton round onClick={() => (forms.removeVisiable1 = false)}>
                取消
              </NButton>
            </NSpace>
          </div>
        </NModal>

        <PreviewWindow
          v-model:show={forms.previewModal}
          type="attend"
          params={forms.previewParams}
        />

        {/* 完成编辑时，选择声部 */}
        <NModal
          v-model:show={forms.subjectSyncVisiable}
          preset="card"
          class={['modalTitle background', styles.subjectSyncModal]}
          title={'同步声部'}>
          <SubjectSync
            subjectId={prepareStore.getSubjectId as any}
            onClose={() => (forms.subjectSyncVisiable = false)}
            onConfirm={async (subjectIds: any) => {
              //
              try {
                forms.editSubjectIds = subjectIds.join(',');
                await onOverEdit();
                forms.subjectSyncVisiable = false;
              } catch {
                //
              }
            }}
          />
        </NModal>
      </div>
    );
  }
});
