import { defineComponent, onMounted, reactive, ref, toRef } from 'vue';
import styles from './index.module.less';
import { NInput, NModal, NScrollbar, NSelect, NSpin, NThing } from 'naive-ui';
import { useRouter } from 'vue-router';
import { BOOK_DATA } from '/src/views/natural-resources/model/add-teaching';
import { classGroupPage, courseScheduleStart } from '../../api';
import { useThrottleFn } from '@vueuse/core';
import TheEmpty from '/src/components/TheEmpty';
import { usePrepareStore } from '/src/store/modules/prepareLessons';
import { modalClickMask, state } from '/src/state';
import { nextTick } from 'process';
import UpdateSubject from '/src/views/classList/modals/updateSubject';
import { api_getCurrentGradeYear } from '/src/views/studentList/api';
const classList: any = [];
for (let i = 1; i <= 40; i++) {
  classList.push({ label: i + '班', value: i });
}

export default defineComponent({
  name: 'attend-class',
  props: {
    // change 切换班级 select 直接进入上课
    type: {
      type: String,
      default: 'change'
    }
  },
  emits: ['close', 'preview', 'confirm'],
  setup(props, { emit }) {
    // const { type } = toRef(props);
    const prepareStore = usePrepareStore();
    const forms = reactive({
      showSubjectClass: false,
      activeRow: {} as any,
      keyword: null,
      currentGradeNum: null,
      currentClass: null
    });
    const gradeYear = ref(null as any);

    const list = ref([] as any);
    const loading = ref(false);
    // 开始上课
    const onAttendClass = async (item: any) => {
      // console.log(item, 'onAttendClass');
      try {
        // 判断是否是切换班级
        if (props.type == 'change') {
          if (item.instrumentId) {
            emit('confirm', {
              lastUseCoursewareId: item.lessonCoursewareId,
              unit: item.lessonCoursewareKnowledgeDetailId,
              instrumentId: prepareStore.getInstrumentId, // item.instrumentId,
              courseScheduleSubjectId: item.courseScheduleSubjectId,
              name: item.name, // 班级名称
              classGroupId: item.id, // 班级编号
              preStudentNum: item.preStudentNum
            });
          } else {
            forms.showSubjectClass = true;
            forms.activeRow = item;
          }
          return;
        }

        const res = await courseScheduleStart({
          lessonCoursewareKnowledgeDetailId: prepareStore.selectKey,
          classGroupId: item.id,
          instrumentId: prepareStore.getInstrumentId
        });

        emit('close');
        emit('preview', {
          type: 'class',
          classId: res.data, // 上课编号
          classGroupId: item.id,
          instrumentId: prepareStore.getInstrumentId,
          detailId: prepareStore.getSelectKey,
          lessonCourseId: prepareStore.getBaseCourseware.id,
          preStudentNum: item.preStudentNum
        });
        if (window.matchMedia('(display-mode: standalone)').matches) {
          state.application = window.matchMedia(
            '(display-mode: standalone)'
          ).matches;
          setTimeout(() => {
            fscreen();
          }, 200);
        }
      } catch {
        //
      }
    };
    const fscreen = () => {
      const el: any = document.documentElement;
      const documentDom: any = document;
      const isFullscreen =
        documentDom.fullScreen ||
        documentDom.mozFullScreen ||
        documentDom.webkitIsFullScreen;
      if (!isFullscreen) {
        //进入全屏
        (el.requestFullscreen && el.requestFullscreen()) ||
          (el.mozRequestFullScreen && el.mozRequestFullScreen()) ||
          (el.webkitRequestFullscreen && el.webkitRequestFullscreen()) ||
          (el.msRequestFullscreen && el.msRequestFullscreen());
      } else {
        //退出全屏
        documentDom.exitFullscreen
          ? documentDom.exitFullscreen()
          : documentDom.mozCancelFullScreen
          ? documentDom.mozCancelFullScreen()
          : documentDom.webkitExitFullscreen
          ? documentDom.webkitExitFullscreen()
          : '';
      }
    };
    const getList = async () => {
      loading.value = true;
      try {
        const { data } = await classGroupPage({
          page: 1,
          rows: 99,
          gradeYear: gradeYear.value,
          upgradeFlag: true,
          ...forms
        });
        const result = data.rows || [];
        const temp: any = [];
        result.forEach((item: any) => {
          // 判断班级里面有学生的
          // if (item.preStudentNum > 0) {
          temp.push(item);
          // }
        });
        list.value = temp;
      } catch {
        //
      }
      loading.value = false;
    };

    const throttleFn = useThrottleFn(() => getList(), 500);

    const getCurrentGradeYears = async () => {
      try {
        const { data } = await api_getCurrentGradeYear({});
        gradeYear.value = data;
      } catch {
        //
      }
    };

    onMounted(async () => {
      loading.value = true;
      await getCurrentGradeYears();
      getList();
    });

    return () => (
      <div class={styles.attendClass}>
        <div class={styles.attendClassSearch}>
          <NInput
            placeholder="请输入班级名称"
            clearable
            v-model:value={forms.keyword}
            onKeyup={(e: KeyboardEvent) => {
              if (e.code === 'Enter') {
                throttleFn();
              }
            }}
            onClear={() => throttleFn()}>
            {{
              prefix: () => (
                <span
                  class="icon-search-input"
                  onClick={() => throttleFn()}></span>
              )
            }}
          </NInput>
          <NSelect
            placeholder="全部年级"
            clearable
            options={
              [{ label: '全部年级', value: null }, ...BOOK_DATA.grades] as any
            }
            v-model:value={forms.currentGradeNum}
            onUpdate:value={() => throttleFn()}
          />
          <NSelect
            placeholder="全部班级"
            clearable
            options={[{ label: '全部班级', value: null }, ...classList]}
            v-model:value={forms.currentClass}
            onUpdate:value={() => throttleFn()}
          />
        </div>
        <NScrollbar class={styles.classList}>
          <NSpin show={loading.value}>
            <div
              class={[
                styles.listSection,
                !loading.value && list.value.length <= 0
                  ? styles.emptySection
                  : ''
              ]}>
              {list.value.map((item: any) => (
                <div onClick={() => onAttendClass(item)}>
                  <NThing class={[styles.thingItem, 'isFull']}>
                    {{
                      header: () => (
                        <>
                          <div class={styles.title}>
                            {item.name} {item.preStudentNum}人
                          </div>
                          <div
                            class={[
                              styles.subjects,
                              item.instrumentName ? '' : styles.noSubjects
                            ]}>
                            {item.instrumentName
                              ? item.instrumentName
                              : '暂无乐器'}
                          </div>
                        </>
                      ),
                      default: () =>
                        item.lastStudy && (
                          <div class={styles.content}>{item.lastStudy}</div>
                        )
                    }}
                  </NThing>
                </div>
              ))}
              {!loading.value && list.value.length <= 0 && <TheEmpty />}
            </div>
          </NSpin>
        </NScrollbar>

        <NModal
          maskClosable={modalClickMask}
          v-model:show={forms.showSubjectClass}
          style={{ width: '500px' }}
          preset="card"
          class={['modalTitle background']}
          title={'修改乐器'}>
          {forms.showSubjectClass ? (
            <UpdateSubject
              activeRow={forms.activeRow}
              onGetList={() => getList()}
              onConfirm={(item: any) => {
                //
                emit('confirm', item);
              }}
              onClose={() => (forms.showSubjectClass = false)}
            />
          ) : null}
        </NModal>
      </div>
    );
  }
});
