import {
  defineComponent,
  onBeforeUnmount,
  onMounted,
  reactive,
  ref
} from 'vue';
import styles from './index.module.less';
import {
  NImage,
  NButton,
  NAvatarGroup,
  NForm,
  NFormItem,
  NSelect,
  NPopselect,
  NSpace,
  NModal,
  NCascader,
  useMessage,
  NSpin
} 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 iconLession from './images/icon-lession.png';
import iconBook from './images/icon-book.png';
import iconDetail from './images/icon-detail.png';
import iconSubject from './images/icon-subject.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 { getCLassStudent, getCourseChapter } from '../classList/api';
import { useCatchStore } from '/src/store/modules/catchData';
import { useThrottleFn } from '@vueuse/core';
import {
  bookVersionPage,
  courseScheduleStart,
  lessonCoursewarePage,
  queryCourseware
} from '../prepare-lessons/api';
import TheNoticeBar from '/src/components/TheNoticeBar';
import TeachGroup from './modals/teachGroup';
import { classGroupList, courseSchedulePage } from './api';
import TheEmpty from '/src/components/TheEmpty';
import { setTabsCaches } from '/src/hooks/use-async';
import HomeGuide from '/src/custom-plugins/guide-page/home-guide';
import TimerMeter from '/src/components/timerMeter';
import { vaildUrl } from '/src/utils/urlUtils';
import toneImage from '@/components/layout/images/toneImage.png';
import { px2vw } from '/src/utils';
import PlaceholderTone from '@/components/layout/modals/placeholderTone';
import { state } from '/src/state';
import { fscreen } from '@/utils/index';
import PreviewWindow from '../preview-window';
import UpdatePassword from '/src/components/layout/modals/update-password';
import { state as globalState } 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 message = useMessage();
    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({
      applyClassItem: {} as any, // 选择的内容
      applyStatus: 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, // 上课数量
      classSelect: {
        currentGradeNum: null,
        currentClass: null,
        name: ''
      } as any,
      popSelectOptions: [] as any,
      showGuide: false,
      showPreview: false,
      itemPreview: {} as any
    });
    const teachList = ref({} as any);

    // 学生列表
    // getStdentList
    // 应用选择年级班级
    const onApplyConfirm = async (item: any) => {
      try {
        //
        const { data } = await getCLassStudent({
          page: 1,
          rows: 999,
          classGroupId: item.classGroupId
        });

        const temps = data.rows || [];
        temps.forEach((row: any) => {
          forms.studentList.push({
            name: row.nickname,
            src: row.avatar
          });
        });
        forms.applyClassItem = item;
      } catch {
        //
      }
    };

    const onUseConfirm = (item: any) => {
      forms.classSelect = {
        currentGradeNum: item.currentGradeNum,
        currentClass: item.classGroupId,
        name: item.name
      };

      getCourseSchedulePage();
    };
    const throttledFn = useThrottleFn(() => getLessonCourseware(), 500);
    const getLessonCourseware = async () => {
      forms.category = null;
      forms.unit = null;
      forms.category = null;
      forms.loading = true;

      try {
        const { data } = await lessonCoursewarePage({
          bookVersionId: forms.bookVersionId,
          enableFlag: 1,
          page: 1,
          rows: 99,
          type: 'COURSEWARE'
          // currentGradeNum: forms.applyClassItem.currentGradeNum
        });

        forms.list = data.rows.map((item: any) => {
          return {
            label: item.name,
            value: item.id
          };
        });
      } catch {
        //
      }

      forms.loading = false;
    };

    const getunitList = async () => {
      forms.unit = null;
      try {
        if (forms.category) {
          const res = await getCourseChapter(forms.category);
          forms.unitList = res.data.lessonList.map((item: any) => {
            return { ...item, label: item.name, value: item.id };
          });
        } else {
          forms.unitList = [];
        }
      } catch (e) {
        console.log(e);
      }
    };
    const getVersion = async () => {
      forms.unit = null;

      try {
        const { data } = await bookVersionPage({
          page: 1,
          rows: 99,
          type: 'COURSEWARE'
        });
        const temp = data.rows || [];
        temp.forEach((item: any) => {
          forms.musicTagList.push({
            id: item.id,
            name: item.name
          });
        });
      } catch {
        //
      }
    };

    // 获取年级班级
    const getClassList = async () => {
      try {
        const { data } = await classGroupList({ removeZeroClass: true });
        const cList = data || [];
        const gradeList: any = [];
        const popSelectOptions: any = [];
        cList.forEach((item: any, index: number) => {
          if (index === 0) {
            const temp = item.classGroupList[0];
            forms.classSelect = {
              currentGradeNum: item.currentGradeNum,
              currentClass: temp.id,
              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 getCourseSchedulePage = async () => {
      forms.classLoading = true;
      try {
        const { data } = await courseSchedulePage({
          classGroupId: forms.classSelect.currentClass,
          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
          });
        });

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

      forms.classLoading = false;
    };

    onMounted(async () => {
      await getClassList();

      await catchStore.getSubjects();

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

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

    const formsRef = ref();
    const gotoClassPage = () => {
      formsRef.value.validate(async (error: any) => {
        if (error) return;
        try {
          const { data } = await queryCourseware({
            coursewareDetailKnowledgeId: forms.unit,
            subjectId: forms.subjectId,
            page: 1,
            rows: 99
          });
          if (data.rows && data.rows.length > 0) {
            await courseScheduleStart({
              lessonCoursewareKnowledgeDetailId: forms.unit,
              classGroupId: forms.applyClassItem?.classGroupId
            });

            if (window.matchMedia('(display-mode: standalone)').matches) {
              forms.showPreview = true;
              forms.itemPreview = {
                type: 'class',
                classGroupId: forms.applyClassItem?.classGroupId,
                subjectId: forms.subjectId,
                detailId: forms.unit
              };
              globalState.application = window.matchMedia(
                '(display-mode: standalone)'
              ).matches;
              // 加全屏
              fscreen();
            } else {
              const { href } = router.resolve({
                path: '/attend-class',
                query: {
                  type: 'class',
                  classGroupId: forms.applyClassItem?.classGroupId,
                  subjectId: forms.subjectId,
                  detailId: forms.unit
                }
              });
              window.open(href, +new Date() + '');
            }
          } else {
            message.error('当前章节暂无课件，请重新选择');
          }
        } catch {
          //
        }
      });
    };
    const clearStorng = () => {
      localStorage.removeItem('teacher-guideInfo');
      forms.showGuide = false;
      setTimeout(() => {
        forms.showGuide = true;
      }, 500);
    };

    return () => (
      <div class={styles.homeWrap}>
        <div class={styles.homeInfoLeft}>
          <div class={styles.homeBanner}>
            {/* <div class={styles.welcomeInfo}>
              <div class={styles.userInfo}>
                <div class={styles.userName}>
                  Hi，{userStore.getUserInfo?.nickname} {formatDateToDay()}～
                </div>
                <div class={styles.userTime}>
                  {dayjs().format('MM月DD日')}，{weekToCN[dayjs().day()]}
                </div>
              </div>
              <div class={styles.userTips}>
                <span>欢迎您使用酷乐秀课堂乐器数字化教学平台！</span>
                <NButton color="#40A1FF" round class={styles.guide_btn} {...{id:'home-1'}}  onClick={()=>clearStorng()}>
                  功能引导
                  <i></i>
                </NButton>
              </div>
            </div> */}
            {/* <div class={styles.centerInfo}>11111</div> */}
            <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 class={styles.userTime}>
                  {dayjs().format('MM月DD日')}，{weekToCN[dayjs().day()]}
                </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.applyTitle}>
                  <span
                    class={styles.className}
                    onClick={() => (forms.applyStatus = true)}>
                    {forms.applyClassItem.name || '请选择班级'}
                  </span>
                  <NAvatarGroup options={forms.studentList} max={5} />
                </div>
                <div class={styles.informations}>
                  {forms.applyClassItem.lastStudy ? (
                    <>
                      <span style="flex-shrink: 0;">上次课程：</span>
                      <TheNoticeBar text={forms.applyClassItem.lastStudy} />
                    </>
                  ) : (
                    ''
                  )}
                </div>

                <NForm showLabel={false} ref={formsRef} model={forms}>
                  <NFormItem
                    path="bookVersionId"
                    rule={[
                      {
                        required: true,
                        message: '',
                        trigger: ['blur', 'change']
                      }
                    ]}>
                    <div class={styles.selectContainer}>
                      <img src={iconLession} />
                      <NSelect
                        placeholder="请选择教材版本"
                        disabled={
                          forms.applyClassItem?.currentGradeNum ? false : true
                        }
                        clearable
                        options={[...forms.musicTagList]}
                        labelField="name"
                        valueField="id"
                        v-model:value={forms.bookVersionId}
                        onUpdate:value={() => throttledFn()}
                      />
                    </div>
                  </NFormItem>
                  <NFormItem
                    path="category"
                    rule={[
                      {
                        required: true,
                        message: '',
                        trigger: ['blur', 'change']
                      }
                    ]}>
                    <div class={styles.selectContainer}>
                      <img src={iconBook} />
                      <NSelect
                        placeholder="请选择册别"
                        options={[...forms.list]}
                        clearable
                        disabled={!forms.bookVersionId}
                        v-model:value={forms.category}
                        onUpdate:value={() => getunitList()}
                      />
                    </div>
                  </NFormItem>
                  <NFormItem
                    path="unit"
                    rule={[
                      {
                        required: true,
                        message: '',
                        trigger: ['blur', 'change']
                      }
                    ]}>
                    <div class={styles.selectContainer}>
                      <img src={iconDetail} />
                      <NCascader
                        disabled={!forms.category}
                        {...({
                          options: [...forms.unitList],
                          placeholder: '选择章节',
                          clearable: true
                        } as any)}
                        childrenField="knowledgeList"
                        valueField="id"
                        labelField="name"
                        v-model:value={forms.unit}
                        checkStrategy="child"
                        expandTrigger="hover"
                      />
                    </div>
                  </NFormItem>
                  <NFormItem
                    path="subjectId"
                    rule={[
                      {
                        required: true,
                        message: '',
                        trigger: ['blur', 'change'],
                        type: 'number'
                      }
                    ]}>
                    <div class={styles.selectContainer}>
                      <img src={iconSubject} />
                      <NSelect
                        {...({
                          options: [...forms.subjectList],
                          placeholder: '选择乐器',
                          clearable: true
                        } as any)}
                        v-model:value={forms.subjectId}
                      />
                    </div>
                  </NFormItem>
                  <NSpace class={styles.btnGroup} justify="center">
                    <NButton
                      round
                      block
                      class={styles.startClass}
                      color="#FF6E4C"
                      onClick={gotoClassPage}>
                      开始上课
                    </NButton>
                    <NButton
                      round
                      block
                      class={styles.beforClass}
                      color="#5B64D1"
                      onClick={() => {
                        // 携带默认数据显示
                        formsRef.value.validate(async (error: any) => {
                          if (error) return;

                          router.push({
                            path: '/prepare-lessons',
                            query: {
                              lastUseCoursewareId: forms.category,
                              unit: forms.unit,
                              subjectId: forms.subjectId
                            }
                          });
                        });
                      }}>
                      去备课
                    </NButton>
                  </NSpace>
                </NForm>
              </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]}
                onClick={() => {
                  showModalBeat.value = true;
                }}>
                <img src={t1} />
                <p class={styles.toolMemo}>提升效率，练习好节奏</p>
                <NButton class={styles.btn1}>节拍器</NButton>
              </div>
              <div
                class={[styles.toolItem, styles.item2]}
                onClick={() => {
                  showModalTone.value = true;
                }}>
                <img src={t2} />
                <p class={styles.toolMemo}>精准调音，一劳永逸</p>
                <NButton class={styles.btn2}>调音器</NButton>
              </div>
              <div
                class={[styles.toolItem, styles.item3]}
                onClick={() => {
                  showModalTime.value = true;
                }}>
                <img src={t3} />
                <p class={styles.toolMemo}>创造时间，集中注意力</p>
                <NButton class={styles.btn3}>计时器</NButton>
              </div>
            </div>
          </div>
        </div>
        <div class={styles.homeInfoRight}>
          <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>
              {forms.classSelect.name && (
                <NPopselect
                  v-model:value={forms.classSelect.currentClass}
                  options={forms.popSelectOptions}
                  trigger="click"
                  onUpdate:value={(val: any) => {
                    console.log(val, '1212');
                    forms.popSelectOptions.forEach((item: any) => {
                      if (item.value === val) {
                        forms.classSelect = {
                          currentGradeNum: item.currentGradeNum,
                          currentClass: item.value,
                          name: item.label
                        };
                        getCourseSchedulePage();
                      }
                    });
                  }}>
                  <div
                    class={styles.lookMore}
                    // onClick={() => (forms.useStatus = true)}
                  >
                    {forms.classSelect.name}
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
                      <path
                        d="M6 9l6 6l6-6"
                        fill="none"
                        stroke="currentColor"
                        stroke-width="2"
                        stroke-linecap="round"
                        stroke-linejoin="round"></path>
                    </svg>
                  </div>
                </NPopselect>
              )}
            </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>
                  ))}
                  {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
                            }
                          });
                        }}>
                        查看全部
                      </span>
                    </div>
                  )}
                </div>
              )}

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

        {/* 添加自定义教材 */}
        <NModal
          v-model:show={forms.applyStatus}
          preset="card"
          showIcon={false}
          class={['modalTitle background', styles.assignHomework]}
          title={'选择班级'}
          blockScroll={false}>
          <SelectClass
            useDetail={{
              currentGradeNum: forms.applyClassItem.currentGradeNum,
              classGroupId: forms.applyClassItem.classGroupId
            }}
            gradeList={forms.gradeList}
            onConfirm={(item: any) => onApplyConfirm(item)}
            onClose={() => (forms.applyStatus = false)}
          />
        </NModal>

        <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>
      </div>
    );
  }
});
