import { defineComponent, onMounted, reactive, ref } from 'vue';
import styles from './index.module.less';
import { NInput, 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';

const classList: any = [];
for (let i = 1; i <= 40; i++) {
  classList.push({ label: i + '班', value: i });
}

export default defineComponent({
  name: 'attend-class',
  emits: ['close'],
  setup(props, { emit }) {
    const prepareStore = usePrepareStore();
    const router = useRouter();
    const forms = reactive({
      keyword: null,
      currentGradeNum: null,
      currentClass: null
    });
    const list = ref([] as any);
    const loading = ref(false);
    // 开始上课
    const onAttendClass = async (item: any) => {
      try {
        await courseScheduleStart({
          lessonCoursewareKnowledgeDetailId: prepareStore.selectKey,
          classGroupId: item.id
        });
        emit('close');

        const { href } = router.resolve({
          path: '/attend-class',
          query: {
            type: 'class',
            classGroupId: item.id,
            subjectId: prepareStore.getSubjectId,
            detailId: prepareStore.getSelectKey,
            classGroupId: item.id
          }
        });
        window.open(href, +new Date() + '');
      } catch {
        //
      }
    };

    const getList = async () => {
      loading.value = true;
      try {
        const { data } = await classGroupPage({
          page: 1,
          rows: 99,
          ...forms
        });
        list.value = data.rows || [];
      } catch {
        //
      }
      loading.value = false;
    };

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

    onMounted(() => {
      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}>
                    {{
                      header: () => (
                        <div class={styles.title}>
                          {item.name} {item.preStudentNum}人
                        </div>
                      ),
                      default: () =>
                        item.lastStudy && (
                          <div class={styles.content}>{item.lastStudy}</div>
                        )
                    }}
                  </NThing>
                </div>
              ))}
              {!loading.value && list.value.length <= 0 && <TheEmpty />}
            </div>
          </NSpin>
        </NScrollbar>
      </div>
    );
  }
});
