import { defineComponent, onMounted, reactive, ref } from 'vue';
import styles from './index.module.less';
import { useUserStore } from '/src/store/modules/users';
import { useRouter } from 'vue-router';
import { NSelect, NSpin } from 'naive-ui';
import {
  classGroupList,
  courseSchedulePage,
  getGradeLevelList,
  getGradeYearList
} from '../../api';
import dayjs from 'dayjs';
import TeachGroup from '../teachGroup';
import TheEmpty from '/src/components/TheEmpty';
import { gradeToCN } from '/src/utils/contants';

export default defineComponent({
  name: 'class-modal',
  emits: ['confirm'],
  setup(props, { emit }) {
    const router = useRouter();
    const userStore = useUserStore();
    const forms = reactive({
      showAttendClass: false,
      // useStatus: false,
      studentList: [] as any,
      bookVersionId: null,
      classGroupId: null,
      category: null,
      subjectId: null,
      musicTagList: [] as any,
      loading: false,
      list: [] as any,
      unit: null,
      unitList: [],
      subjectList: [] as any,
      gradeList: [] as any,
      classLoading: false,
      total: 0, // 上课数量
      // 上次上课的数据
      lastClassSelect: {
        currentClass: null,
        name: '',
        upgradeFlag: false, // 是否为历史班
        gradeYear: null as any,
        gradeLevel: null as any
      },
      classSelect: {
        currentGradeNum: null,
        currentClass: null,
        name: '',
        upgradeFlag: false, // 是否为历史班
        gradeLevel: null as any,
        gradeYear: null
      } as any,
      popSelectOptions: [] as any,
      popSelectYearList: [] as any,
      popSelectLevelList: [] as any,
      showGuide: false,
      showPreview: false,
      itemPreview: {} as any,
      homeLeftHeight: 'auto'
    });
    const teachList = ref({} as any);

    // 获取年级班级
    const getClassList = async () => {
      try {
        const { data } = await classGroupList({
          gradeLevel: forms.classSelect.gradeLevel,
          gradeYear: forms.classSelect.gradeYear
        });
        const cList = data || [];
        const gradeList: any = [];
        const popSelectOptions: any = [];
        // getLastClassRecode()
        cList.forEach((item: any, index: number) => {
          // 判断是否已经有班级了
          if (index === 0) {
            if (forms.lastClassSelect.currentClass) {
              forms.classSelect.currentClass =
                forms.lastClassSelect.currentClass;
              forms.classSelect.name = forms.lastClassSelect.name;
              forms.classSelect.upgradeFlag = forms.lastClassSelect.upgradeFlag;
            } else {
              const temp = item.classGroupList[0];
              forms.classSelect.currentGradeNum = item.currentGradeNum;
              forms.classSelect.currentClass = temp.id;
              forms.classSelect.name = temp.name;
            }
          }

          const classList: any = [];
          item.classGroupList.forEach((i: any) => {
            classList.push({
              label: i.currentClass + '班',
              value: i.id,
              lastStudy: i.lastStudy
            });

            popSelectOptions.push({
              label: i.name,
              value: i.id,
              currentGradeNum: item.currentGradeNum,
              lastStudy: i.lastStudy
            });
          });

          gradeList.push({
            label: gradeToCN[item.currentGradeNum],
            value: item.currentGradeNum,
            childrens: classList
          });
        });
        forms.popSelectOptions = popSelectOptions;
        forms.gradeList = gradeList;
      } catch {
        //
      }
    };
    const getLastClassRecode = async () => {
      const { data } = await courseSchedulePage({
        page: 1,
        rows: 1,
        teacherId: userStore.getUserInfo.id
      });
      if (data.rows.length > 0 && data.rows[0]) {
        const tempRow = data.rows[0];
        // forms.lastClassSelect.currentClass = tempRow.classGroupId;
        // forms.lastClassSelect.name = tempRow.classGroupName;
        forms.lastClassSelect = {
          currentClass: tempRow.classGroupId,
          name: tempRow.classGroupName,
          upgradeFlag: tempRow.upgradeFlag,
          gradeYear: tempRow.gradeYear + '',
          gradeLevel: tempRow.gradeLevel + ''
        };
      }
    };

    // 获取学年
    const getYearList = async () => {
      try {
        const { data } = await getGradeYearList();
        const temp = data || [];
        temp.forEach((i: any) => {
          i.name = i.name + '学年';
        });
        forms.popSelectYearList = temp || [];
        if (temp.length > 0) {
          if (forms.lastClassSelect.gradeYear) {
            forms.classSelect.gradeYear = forms.lastClassSelect.gradeYear;
          } else {
            forms.classSelect.gradeYear = temp[0].id;
          }
        }
      } catch (e: any) {
        //
      }
    };
    // 获取学级
    const getLevelList = async () => {
      try {
        const { data } = await getGradeLevelList();
        const temp = data || [];
        temp.forEach((i: any) => {
          i.name = i.name + '级';
        });
        temp.unshift({
          id: '',
          name: '全部学级'
        });
        forms.popSelectLevelList = temp || [];
        if (temp.length > 0) {
          if (forms.lastClassSelect.gradeLevel) {
            forms.classSelect.gradeLevel =
              forms.lastClassSelect.gradeLevel + '';
          } else {
            forms.classSelect.gradeLevel = temp[0].id;
          }
        }
      } catch {
        //
      }
    };

    const getCourseSchedulePage = async () => {
      forms.classLoading = true;
      try {
        const { data } = await courseSchedulePage({
          classGroupId: forms.classSelect.currentClass,
          gradeLevel: forms.classSelect.gradeLevel,
          gradeYear: forms.classSelect.gradeYear,
          page: 1,
          rows: 4,
          teacherId: userStore.getUserInfo.id
        });

        const result = data.rows || [];
        forms.total = data.total || 0;
        const dateTime: any = {};
        result.forEach((item: any) => {
          const tempTime = dayjs(item.classDate).format('MM-DD');
          if (!dateTime[tempTime]) {
            dateTime[tempTime] = [];
          }

          const lessonCourseware = item.lessonCoursewareJson
            ? JSON.parse(item.lessonCoursewareJson)
            : {};
          dateTime[tempTime].push({
            classGroup: forms.classSelect.name,
            teacherName: item.teacherName,
            conent:
              lessonCourseware.lessonCoursewareName +
              ' | ' +
              lessonCourseware.lessonCoursewareDetailName +
              ' | ' +
              lessonCourseware.lessonCoursewareKnowledgeDetailName +
              ' | ' +
              (lessonCourseware.useChapterLessonCoursewareName || ''),
            image: item.teacherAvatar,
            subjectName: item.instrumentName
          });
        });

        teachList.value = dateTime;
      } catch (e: any) {
        //
        console.log(e);
      }

      forms.classLoading = false;
    };

    onMounted(async () => {
      forms.classLoading = true;
      await getLastClassRecode();

      await getYearList();
      await getLevelList();
      await getClassList();
      // await catchStore.getSubjects();

      await getCourseSchedulePage();
      forms.classLoading = false;
    });
    return () => (
      <div>
        <div class={styles.rightTeachingWrap}>
          <div class={styles.rightTeachingWrapTitle}>
            <div class={styles.classSearchList}>
              <NSelect
                v-model:value={forms.classSelect.gradeYear}
                class={styles.lookMoreSearch}
                placeholder="全部学年"
                options={forms.popSelectYearList}
                labelField="name"
                valueField="id"
                onUpdate:value={async (val: any) => {
                  forms.classSelect.gradeYear = val;
                  forms.lastClassSelect.currentClass = null;
                  forms.classSelect.currentClass = null;
                  await getClassList();
                  await getCourseSchedulePage();
                }}></NSelect>
              <NSelect
                v-model:value={forms.classSelect.gradeLevel}
                class={styles.lookMoreSearch}
                placeholder="全部学级"
                options={forms.popSelectLevelList}
                labelField="name"
                valueField="id"
                onUpdate:value={async (val: any) => {
                  forms.classSelect.gradeLevel = val;
                  forms.lastClassSelect.currentClass = null;
                  forms.classSelect.currentClass = null;
                  await getClassList();
                  await getCourseSchedulePage();
                }}></NSelect>
              <NSelect
                v-model:value={forms.classSelect.currentClass}
                class={styles.lookMoreSearch}
                placeholder="选择班级"
                options={forms.popSelectOptions}
                onUpdate:value={(val: any) => {
                  forms.popSelectOptions.forEach((item: any) => {
                    if (item.value === val) {
                      forms.classSelect.currentGradeNum = item.currentGradeNum;
                      forms.classSelect.currentClass = item.value;
                      forms.classSelect.name = item.label;
                      forms.classSelect.upgradeFlag = item.upgradeFlag;
                      getCourseSchedulePage();
                    }
                  });
                }}></NSelect>
            </div>
          </div>
          <NSpin show={forms.classLoading} style={{ minHeight: '40vh' }}>
            {Object.keys(teachList.value).length > 0 && (
              <div class={styles.teachListWrap}>
                {Object.keys(teachList.value).map(key => (
                  <TeachGroup
                    list={teachList.value[key]}
                    keys={key}></TeachGroup>
                ))}
              </div>
            )}

            {Object.keys(teachList.value).length <= 0 &&
              !forms.classLoading && (
                <div class={styles.emptySection}>
                  <TheEmpty />
                </div>
              )}
          </NSpin>

          {forms.total > 4 && (
            <div class={styles.teachListWrapWall}>
              <span
                onClick={() => {
                  // setTabsCaches('attendclass', 'tabName', {
                  //   path: '/classDetail'
                  // });
                  emit('confirm');
                  sessionStorage.setItem('classDetailTabs', 'attendclass');
                  router.push({
                    path: '/classDetail',
                    query: {
                      name: forms.classSelect.name,
                      id: forms.classSelect.currentClass,
                      gradeYear: forms.classSelect.gradeYear,
                      upgradeFlag: forms.classSelect.upgradeFlag ? 1 : 0, // 是否为历史班
                      v: +new Date()
                    }
                  });
                }}>
                查看全部
              </span>
            </div>
          )}
        </div>
      </div>
    );
  }
});
