import { defineComponent, onMounted, reactive, ref } from 'vue';
import styles from './index.module.less';
import {
  NImage,
  NButton,
  NPopselect,
  NModal,
  useMessage,
  NSpin,
  NSelect
} from 'naive-ui';
import headerD from './images/headerD.png';
import defultHeade from '@/components/layout/images/teacherIcon.png';
import blackBoardBg from './images/blackboard_bg.png';
import teacherMan from './images/teacher_man.png';
import teacherWoman from './images/teacher_woman.png';

import homeText1 from './images/home/home-text-1.png';
import homeText2 from './images/home/home-text-2.png';
import iconTo from './images/icon-to.png';
import t1 from './images/t1.png';
import t2 from './images/t2.png';
import t3 from './images/t3.png';
import { useRouter } from 'vue-router';
import { useUserStore } from '/src/store/modules/users';
// import SelectClass from './modals/selectClass';
import dayjs from 'dayjs';
import { gradeToCN, weekToCN } from '/src/utils/contants';
import { useCatchStore } from '/src/store/modules/catchData';
import TeachGroup from './modals/teachGroup';
import {
  classGroupList,
  courseSchedulePage,
  getGradeLevelList,
  getGradeYearList
} from './api';
import TheEmpty from '/src/components/TheEmpty';
import HomeGuide from '/src/custom-plugins/guide-page/home-guide';
import TimerMeter from '/src/components/timerMeter';
import { vaildUrl } from '/src/utils/urlUtils';
import { px2vw } from '/src/utils';
import PlaceholderTone from '@/components/layout/modals/placeholderTone';
import PreviewWindow from '../preview-window';
import UpdatePassword from '/src/components/layout/modals/update-password';
import AttendClass from '../prepare-lessons/model/attend-class';
import { useResizeObserver } from '@vueuse/core';
// import { state } from '/src/state';
export const formatDateToDay = () => {
  const hours = dayjs().hour();
  if (hours < 12) {
    return '早上好'; //如果小时数小于12则输出“早上好！”
  } else if (hours > 12 && hours < 18) {
    return '下午好'; //如果小时数大于12并且小于18，输入“下午好！”
  } else {
    return '晚上好'; //如果上面两个条件都不符合，则输出“晚上好！”
  }
};

export default defineComponent({
  name: 'home-page',
  setup() {
    const catchStore = useCatchStore();
    const router = useRouter();
    const userStore = useUserStore();
    const showUpdatePassword = ref(false);
    const showModalBeat = ref(false);
    const showModalTone = ref(false);
    const showModalTime = ref(false);
    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,
            image: item.teacherAvatar,
            subjectName: item.subjectName
          });
        });

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

      forms.classLoading = false;
    };

    onMounted(async () => {
      useResizeObserver(
        document.querySelector('#homeInfoLeft-home') as any,
        (entries: any) => {
          const entry = entries[0];
          const { height } = entry.contentRect;
          forms.homeLeftHeight = height + 'px';
        }
      );

      forms.classLoading = true;
      await getLastClassRecode();

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

      await getCourseSchedulePage();
      // forms.subjectList = catchStore.getSubjectList.map((item: any) => {
      //   return {
      //     label: item.name,
      //     value: item.id
      //   };
      // });

      if (!userStore.getUserInfo.account.updatePasswordFlag) {
        showUpdatePassword.value = true;
      } else {
        forms.showGuide = true;
      }

      forms.classLoading = false;
    });
    // const clearStorng = () => {
    //   localStorage.removeItem('teacher-guideInfo');
    //   forms.showGuide = false;
    //   setTimeout(() => {
    //     forms.showGuide = true;
    //   }, 500);
    // };

    return () => (
      <div class={styles.homeWrap}>
        <div class={styles.homeInfoLeft} id="homeInfoLeft-home">
          <div class={styles.homeBanner}>
            <div class={styles.applyInfo} id="home-1">
              <div class={styles.centerInfo} id="home-0"></div>

              <div class={styles.userInfo}>
                <div class={styles.userName}>
                  Hi，{userStore.getUserInfo?.nickname} {formatDateToDay()}～
                </div>
              </div>
              {userStore.getUserInfo.gender === 1 ? (
                <img src={teacherMan} class={styles.teacherMan} />
              ) : (
                <img src={teacherWoman} class={styles.teacherWoman} />
              )}

              <div class={styles.blackborad}>
                <img src={blackBoardBg} class={styles.blackBoardBg} />
              </div>
              <div class={styles.applyContainer}>
                <div class={[styles.applyItem, styles.applyItem1]}>
                  <p>合理的规划教学内容，让学生更好掌握知识</p>
                  <div
                    class={[styles.applyBtn, styles.applyBtn1]}
                    onClick={() => {
                      // 备课
                      router.push({
                        path: '/prepare-lessons'
                      });
                    }}>
                    <img src={homeText1} />
                  </div>
                </div>
                <div class={[styles.applyItem, styles.applyItem2]}>
                  <p>从这里开始，带领学生在知识的海洋中遨游</p>
                  <div
                    class={[styles.applyBtn, styles.applyBtn2]}
                    onClick={() => {
                      forms.showAttendClass = true;
                    }}>
                    <img src={homeText2} />
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div class={styles.toolContainer}>
            <div class={styles.toolTips}>
              <div class={styles.toolTitle}>工具箱</div>
              <div class={styles.toolContent}>
                这里是常用的教学辅助工具，可帮助学生集中注意力、提高演奏效率，使演奏更完整平稳。让您在课堂上完成更好的教学。
              </div>
            </div>
            <img src={iconTo} class={styles.iconTo} />
            <div class={styles.toolFunction} id="home-3">
              <div class={[styles.toolItem, styles.item1]}>
                <img src={t1} />
                {/* <p class={styles.toolMemo}>提升效率，练习好节奏</p> */}
                <NButton
                  class={styles.btn1}
                  onClick={() => {
                    showModalBeat.value = true;
                  }}>
                  节拍器
                </NButton>
              </div>
              <div class={[styles.toolItem, styles.item2]}>
                <img src={t2} />
                {/* <p class={styles.toolMemo}>精准调音，一劳永逸</p> */}
                <NButton
                  class={styles.btn2}
                  onClick={() => {
                    showModalTone.value = true;
                  }}>
                  调音器
                </NButton>
              </div>
              <div class={[styles.toolItem, styles.item3]}>
                <img src={t3} />
                {/* <p class={styles.toolMemo}>创造时间，集中注意力</p> */}
                <NButton
                  class={styles.btn3}
                  onClick={() => {
                    showModalTime.value = true;
                  }}>
                  计时器
                </NButton>
              </div>
            </div>
          </div>
        </div>
        <div
          class={styles.homeInfoRight}
          style={{ height: forms.homeLeftHeight }}>
          <div class={styles.rightTeachingWrap}>
            <div class={styles.headerContainer}>
              <div
                class={styles.HeaderWrap}
                onClick={() => router.push('/setting')}>
                <NImage
                  previewDisabled
                  class={styles.headerD}
                  src={headerD}></NImage>
                <NImage
                  previewDisabled
                  class={styles.defultHeade}
                  src={userStore.getUserInfo.avatar || defultHeade}></NImage>
              </div>
            </div>
            <div class={styles.headerInfo}>
              <p class={styles.headerTitle}>{userStore.getUserInfo.nickname}</p>
              {userStore.getUserInfo.schoolInfos &&
                userStore.getUserInfo.schoolInfos.length > 0 && (
                  <p class={styles.headerSubTitle}>
                    {userStore.getUserInfo.schoolInfos[0].name}
                    {/* | 音乐老师 */}
                  </p>
                )}
            </div>
            <div class={styles.rightTeachingWrapTitle}>
              <h3 class={styles.rightTitle}>
                <div class={styles.titleDot}></div>上课记录
              </h3>

              <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 && <TheEmpty />}
            </NSpin>

            {forms.total > 4 && (
              <div class={styles.teachListWrapWall}>
                <span
                  onClick={() => {
                    // setTabsCaches('attendclass', 'tabName', {
                    //   path: '/classDetail'
                    // });
                    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 // 是否为历史班
                      }
                    });
                  }}>
                  查看全部
                </span>
              </div>
            )}
          </div>
        </div>

        {/* <NModal
          v-model:show={forms.useStatus}
          preset="card"
          showIcon={false}
          class={['modalTitle background', styles.assignHomework]}
          title={'选择班级'}
          blockScroll={false}>
          <SelectClass
            useDetail={{
              currentGradeNum: forms.classSelect.currentGradeNum,
              classGroupId: forms.classSelect.currentClass
            }}
            gradeList={forms.gradeList}
            onConfirm={(item: any) => onUseConfirm(item)}
            onClose={() => (forms.useStatus = false)}
          />
        </NModal> */}

        <NModal
          class={['modalTitle background']}
          title={'节拍器'}
          preset="card"
          v-model:show={showModalBeat.value}
          style={{ width: '687px' }}>
          <div class={styles.modeWrap}>
            <iframe
              src={`${vaildUrl()}/metronome/?id=${new Date().getTime()}`}
              scrolling="no"
              frameborder="0"
              width="100%"
              height={'650px'}></iframe>
          </div>
        </NModal>

        <NModal
          v-model:show={showModalTime.value}
          class={['modalTitle background']}
          title={'计时器'}
          preset="card"
          style={{ width: px2vw(772) }}>
          <div>
            <TimerMeter></TimerMeter>
          </div>
        </NModal>

        <NModal class={['background']} v-model:show={showModalTone.value}>
          <div>
            <PlaceholderTone
              onClose={() => {
                showModalTone.value = false;
              }}></PlaceholderTone>
          </div>
        </NModal>

        {/* 弹窗查看 */}
        <PreviewWindow
          v-model:show={forms.showPreview}
          type="attend"
          params={forms.itemPreview}
        />

        {forms.showGuide ? <HomeGuide></HomeGuide> : null}

        <NModal
          v-model:show={showUpdatePassword.value}
          class={['modalTitle', styles.showUpdatePassword]}
          style="--n-title-font-weight: 600;"
          preset="card"
          title={'修改密码'}
          closable={false}
          maskClosable={false}
          closeOnEsc={false}>
          <UpdatePassword
            onSubmit={() => {
              // 密码更新成功
              showUpdatePassword.value = true;
              forms.showGuide = true;
              userStore.logout().then(() => {
                // 移除标签页
                router
                  .replace({
                    name: 'login'
                  })
                  .finally(() => location.reload());
              });
            }}
          />
        </NModal>

        <NModal
          v-model:show={forms.showAttendClass}
          preset="card"
          showIcon={false}
          class={['modalTitle background', styles.attendClassModal]}
          title={'选择班级'}
          blockScroll={false}>
          <AttendClass
            onClose={() => (forms.showAttendClass = false)}
            type="change"
            onConfirm={(item: any) => {
              router.push({
                path: '/prepare-lessons',
                query: {
                  ...item
                }
              });
            }}
          />
        </NModal>
      </div>
    );
  }
});
