import { defineComponent, ref, onMounted, nextTick, onUnmounted } from 'vue';
import styles from './index.module.less';
import { NImage, NBadge, NPopover, NIcon, NModal, NTooltip } from 'naive-ui';
import styles2 from './modals/suggestion-option.module.less';
import schoolIcon from './images/schoolIcon.png';
import teacherIcon from './images/teacherIcon.png';
import messageIcon from './images/messageIcon.png';
import closeIcon from './images/closeIcon.png';
import clockIcon from './images/clockIcon.png';
import schoolDot from './images/schoolDot.png';
import personIcon from './images/personIcon.png';
import iconAboutus from './images/icon-aboutus.png';
import { useUserStore } from '@/store/modules/users';
import inFront from './images/inFront.png';
import inBack from './images/inBack.png';
import submitBtn from './images/submitBtn.png';
import sealing from './images/sealing.png';
import boxBg from './images/boxBg.png';
import { useRouter } from 'vue-router';
import { storeToRefs } from 'pinia';
import opinionIcon from './images/opinionIcon.png';
// import inviteIcon from './images/invite_student_icon.png';
import gnydIcon from './images/gnyd.png';
import classHistoryIcon from './images/classHistoryIcon.png';
import 'animate.css';
import ForgotPassword from '/src/views/setting/modal/forgotPassword';
import ImGroup from './imGroup';
import SuggestionOption from './modals/suggestion-option';
import ClassModal from '/src/views/home/modals/class-modal';
import { suggestMessageUnread } from '/src/api/user';
import { eventGlobal } from '/src/utils';
import { usePrepareStore } from '/src/store/modules/prepareLessons';
// import { schoolDetail } from '/src/views/studentList/api';
// import AddStudentModel from '/src/views/studentList/modals/addStudentModel';
import { modalClickMask } from '/src/state';
import { teacherJobType } from '/src/utils/contants';
import GuideSection from './guide-section';
import { GuideDriver } from './guide-section/driver';

export default defineComponent({
  name: 'layoutTop',
  setup() {
    const router = useRouter();
    const noReadCount = ref(0); // 未读数
    const showHeadFlag = ref(false);
    const showImGroup = ref(false);
    const showImGroupLoading = ref(true);
    const showSuggestionViseble = ref(false);
    const users = useUserStore();
    const showWord = ref(false);
    const { info } = storeToRefs(users);
    const userInfoStatus = ref(false);
    const classRecordStatus = ref(false);
    const prepareStore = usePrepareStore();
    const guideSectionRef = ref();
    // const state = reactive({
    //   addStudentVisible: false,
    //   activeRow: {} as any
    // });

    const oncheckEditStatus = (callBack: any) => {
      showHeadFlag.value = false;
      userInfoStatus.value = false;
      if (prepareStore.getIsEditResource) {
        eventGlobal.emit('pageBeforeLeave', () => callBack());
      } else {
        callBack();
      }
    };
    const gotoPerson = () => {
      userInfoStatus.value = false;
      router.push({ path: '/setting', query: { activeTab: 'person' } });
    };
    const gotoSchool = () => {
      router.push({ path: '/setting', query: { activeTab: 'school' } });
    };
    const suggestionOptionRef = ref();
    const resetPwd = () => {
      showHeadFlag.value = false;
      showWord.value = true;
      userInfoStatus.value = false;
    };
    const aboutUs = () => {
      router.push({ path: '/aboutUs' });
    };
    const body = document.querySelector('body');
    if (body) {
      body.className = 'myBody body';
    }

    const showOption = () => {
      showSuggestionViseble.value = true;
      if (suggestionOptionRef.value) {
        suggestionOptionRef.value.onReset();
      }
    };

    // 邀请学生二维码
    // const showInviteQrcode = async () => {
    //   try {
    //     const { schoolInfos } = users.getUserInfo;
    //     const schoolId = schoolInfos.length > 0 ? schoolInfos[0].id : null;
    //     if (schoolId) {
    //       const { data } = await schoolDetail({ id: schoolId });
    //       state.activeRow = data;

    //       state.addStudentVisible = true;
    //     }
    //   } catch {
    //     //
    //   }
    // };

    const suggestionStatus = ref(false);
    const getSuggestMessageUnread = async () => {
      try {
        const { data } = await suggestMessageUnread();
        const temp = data || [];
        let system: any = {};
        temp.forEach((item: any) => {
          if (item.group === 'SYSTEM') {
            system = item;
          }
        });
        if (system.number > 0) {
          suggestionStatus.value = system.number > 0 ? true : false;
        } else {
          suggestionStatus.value = false;
        }
      } catch {
        //
      }
    };

    onMounted(() => {
      window.addEventListener('message', onImMessage);
      showImGroupLoading.value = true;
      showImGroup.value = true;

      getSuggestMessageUnread();

      eventGlobal.on('onSuggestionRead', () => {
        if (suggestionStatus.value) {
          getSuggestMessageUnread();
        }
      });

      nextTick(() => {
        setTimeout(() => {
          showImGroup.value = false;
        }, 50);
        setTimeout(() => {
          showImGroupLoading.value = false;
          if (body) {
            body.className = 'myBody';
          }
        }, 1000);
      });
    });

    const onImMessage = (evt: MessageEvent) => {
      if (evt.data.api === 'onImClose') {
        showImGroup.value = false;
      } else if (evt.data.api === 'getNoReadMessageCount') {
        console.log(evt, 'onMessage');
        noReadCount.value = evt.data.count || 0;
      }
    };

    onUnmounted(() => {
      window.removeEventListener('message', onImMessage);
    });

    const imgList = [inFront, inBack, submitBtn, sealing, boxBg];
    const loadImg = (imgList: any) => {
      for (let i = 0; i < imgList.length; i++) {
        const img = new Image();
        // let currentSrc = ''
        img.src = imgList[i];
        img.onload = function (e) {
          // console.log('加载完毕', e, img.complete);
        };
        img.onerror = function (e) {
          // console.log('加载错误', e);
        };
      }
    };
    loadImg(imgList);

    return () => (
      <div class={[styles.layoutTop, 'layoutTop']}>
        <div class={styles.layoutLeft}>
          <NImage
            src={schoolIcon}
            class={styles.schoolIcon}
            previewDisabled></NImage>
          <p>
            {(info.value?.schoolInfos && info.value?.schoolInfos[0].name) || ''}
          </p>
        </div>
        <div class={styles.layoutRight}>
          <NTooltip showArrow={false}>
            {{
              trigger: () => (
                <div
                  class={[
                    styles.optons,
                    'home-1'
                    // !helpNoteStatus.value && styles.booxToolDisabled
                  ]}
                  id="home-1"
                  onClick={() => {
                    // if (!helpNoteStatus.value) return;
                    // // 默认滚动到页面顶部，在显示指引
                    // document.querySelector('#WrapcoreViewWrap')?.scrollTo(0, 0);
                    // console.log(route.name, 'guideInfo');
                    // eventGlobal.emit('teacher-guideInfo', route.name);

                    guideSectionRef.value?.onToggle();
                  }}>
                  <NImage src={gnydIcon} previewDisabled></NImage>
                </div>
              ),
              default: '操作手册'
            }}
          </NTooltip>
          {/* <NTooltip showArrow={false}>
              {{
                trigger: () => (
                  <div class={styles.optons} onClick={showInviteQrcode}>
                    <NBadge dot={suggestionStatus.value} color={'#FF1036'}>
                      <NImage src={inviteIcon} previewDisabled></NImage>
                    </NBadge>
                  </div>
                ),
                default: '邀请学生'
              }}
            </NTooltip> */}
          <NPopover
            width={380}
            class={styles.popoverClassModel}
            placement={'bottom'}
            v-model:show={classRecordStatus.value}
            trigger="click"
            displayDirective="show"
            v-slots={{
              trigger: () => (
                <NTooltip showArrow={false}>
                  {{
                    trigger: () => (
                      <div class={styles.optons}>
                        <NImage src={classHistoryIcon} previewDisabled></NImage>
                      </div>
                    ),
                    default: '上课记录'
                  }}
                </NTooltip>
              )
            }}>
            <ClassModal
              onConfirm={() => {
                classRecordStatus.value = false;
              }}
            />
          </NPopover>
          <NTooltip showArrow={false}>
            {{
              trigger: () => (
                <div class={styles.optons} onClick={showOption} id="home-2">
                  <NBadge dot={suggestionStatus.value} color={'#FF1036'}>
                    <NImage src={opinionIcon} previewDisabled></NImage>
                  </NBadge>
                </div>
              ),
              default: '意见反馈'
            }}
          </NTooltip>
          {/* </div> */}
          <div onClick={() => (showImGroup.value = true)}>
            <NTooltip showArrow={false}>
              {{
                trigger: () => (
                  <NBadge
                    value={noReadCount.value}
                    max={99}
                    class={[
                      noReadCount.value > 0 ? '' : styles.messageBadgeHide,
                      styles.messageBadge,
                      noReadCount.value > 0 ? '' : styles.messageBadgeNo
                    ]}
                    {...{ id: 'home-3' }}
                    color={'#FF1036'}>
                    <NImage
                      class={[
                        styles.messageIcon,
                        noReadCount.value > 0 ? styles.animation : ''
                      ]}
                      preview-disabled
                      src={messageIcon}></NImage>
                  </NBadge>
                ),
                default: '聊天'
              }}
            </NTooltip>
          </div>

          <div class={styles.line}></div>
          <NPopover
            show-arrow={false}
            trigger="click"
            v-model:show={userInfoStatus.value}
            onUpdate:show={val => {
              showHeadFlag.value = val;
            }}
            class={styles.popoverHeader}
            placement="bottom-end"
            raw={true}
            v-slots={{
              trigger: () => (
                <div class={styles.mesgWrap} style={{ cursor: 'pointer' }}>
                  <NImage
                    preview-disabled
                    class={styles.teacherIcon}
                    src={
                      info.value.avatar ? info.value.avatar : teacherIcon
                    }></NImage>
                  <NIcon
                    class={
                      showHeadFlag.value ? styles.rotueLeft : styles.rotueRight
                    }>
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
                      <path
                        d="M7.38 21.01c.49.49 1.28.49 1.77 0l8.31-8.31a.996.996 0 0 0 0-1.41L9.15 2.98c-.49-.49-1.28-.49-1.77 0s-.49 1.28 0 1.77L14.62 12l-7.25 7.25c-.48.48-.48 1.28.01 1.76z"
                        fill="currentColor"></path>
                    </svg>
                  </NIcon>
                </div>
              )
            }}>
            <div class={styles.propWrap}>
              <div class={styles.teacherInfo}>
                <NImage
                  class={styles.teacherIcon}
                  src={info.value.avatar ? info.value.avatar : teacherIcon}
                  previewDisabled></NImage>
                <div class={styles.userInfos}>
                  <NTooltip class={styles.nameTool}>
                    {{
                      trigger: () => (
                        <p class={styles.teacherName}>{info.value.nickname}</p>
                      ),
                      default: () => info.value.nickname
                    }}
                  </NTooltip>
                  {info.value.teacherJobType && (
                    <span class={styles.roleType}>
                      {teacherJobType[info.value.teacherJobType]}
                    </span>
                  )}
                </div>
              </div>
              <div class={styles.propWrapList}>
                <div
                  class={styles.propWrapItem}
                  onClick={() => oncheckEditStatus(gotoPerson)}>
                  <NImage
                    class={styles.smallIcon}
                    src={personIcon}
                    previewDisabled></NImage>
                  <p class={styles.smallTitle}>个人信息</p>
                </div>
                {info.value.isSuperAdmin ||
                info.value.teacherJobType === 'HEADMASTER' ? (
                  <div
                    class={styles.propWrapItem}
                    onClick={() => {
                      oncheckEditStatus(gotoSchool);
                    }}>
                    <NImage
                      class={styles.smallIcon}
                      src={schoolDot}
                      previewDisabled></NImage>
                    <p class={styles.smallTitle}>学校信息</p>
                  </div>
                ) : null}

                <div class={styles.propWrapItem} onClick={() => resetPwd()}>
                  <NImage
                    class={styles.smallIcon}
                    src={clockIcon}
                    previewDisabled></NImage>
                  <p class={styles.smallTitle}>修改密码</p>
                </div>

                <div
                  class={styles.propWrapItem}
                  onClick={() => oncheckEditStatus(aboutUs)}>
                  <NImage
                    class={styles.smallIcon}
                    src={iconAboutus}
                    previewDisabled></NImage>
                  <p class={styles.smallTitle}>关于我们</p>
                </div>
              </div>
              <div
                class={styles.logoutInfo}
                onClick={() => {
                  users.logout();
                  router.replace('/login')
                  // .then(() => {
                  //   window.location.reload();
                  // });
                }}>
                <div class={styles.propWrapItem}>
                  <NImage
                    class={styles.smallIcon}
                    src={closeIcon}
                    previewDisabled></NImage>
                  <p class={styles.smallTitle}>退出登录</p>
                </div>
              </div>
            </div>
          </NPopover>
          <div class={styles2.isHidden}></div>
        </div>
        <NModal
          maskClosable={modalClickMask}
          class={styles.changePwdModal}
          v-model:show={showWord.value}
          preset="dialog"
          showIcon={false}
          title="修改密码">
          <ForgotPassword
            phone={info.value.phone}
            onClose={() => {
              showWord.value = false;
            }}
          />
        </NModal>

        <NModal
          maskClosable={modalClickMask}
          v-model:show={showImGroup.value}
          showIcon={false}
          class={showImGroupLoading.value ? styles.hideModal : ''}
          {...{ id: 'imGroupDiv' }}
          displayDirective="show">
          <ImGroup />
        </NModal>

        <NModal
          maskClosable={modalClickMask}
          class={['modalTitle', 'background', styles.suggestWrap]}
          v-model:show={showSuggestionViseble.value}
          display-directive="show"
          showIcon={false}>
          <SuggestionOption
            ref={suggestionOptionRef}
            onClose={() =>
              (showSuggestionViseble.value = false)
            }></SuggestionOption>
        </NModal>

        {/* 操作手册 */}
        <GuideSection ref={guideSectionRef} />

        <GuideDriver />
      </div>
    );
  }
});
