import {
  defineComponent,
  onMounted,
  onUnmounted,
  reactive,
  ref,
  nextTick
} from 'vue';
import styles from './index.module.less';
// import signinTips from './images/signin-tips.png';
import {
  Button,
  CellGroup,
  Field,
  Picker,
  Popup,
  closeToast,
  showToast,
  Loading
} from 'vant';
import { useRoute, useRouter } from 'vue-router';
import threeMan from './images/update/three-man.png';
import OWxTip from '@/components/m-wx-tip';
import { browser, getHttpOrigin, getUrlCode } from '@/helpers/utils';
import qs from 'query-string';
import request from '@/helpers/request';
import { goWechatAuth, goWechatAuthTemp } from '@/state';
import { useInterval, useIntervalFn } from '@vueuse/core';
import MMessageTip from '@/components/m-message-tip';
import TCPlayer from 'tcplayer.js';
import 'tcplayer.js/dist/tcplayer.css';
import { _initVideo } from './initVideo';
import nextBtn from './images/next_btn.png';
import useWeChatShare from '@/hooks/useWeChatShare';

export default defineComponent({
  name: 'intention-questionnaire',
  setup() {
    const route = useRoute();
    const shareTitle = route.query.type === 'primarySchoolNo' ? '（小学）关于开展音乐（器乐）课堂数字化转型的调查问卷' :
    route.query.type === 'juniorSchoolNo' ? '（初中）关于开展音乐（器乐）课堂数字化转型的调查问卷' :
    '关于开展音乐（器乐）课堂数字化转型的调查问卷'
    const weChatShare = useWeChatShare(
      shareTitle,
      '科学的教育改变世界，科技的力量让音乐传播更远，让孩子奏响心中的乐章',
      window.location.origin + '/classroom-app/shareImg/question-share.png'
    );

    // 页面定时
    const pageTimer = useInterval(1000, { controls: true });
    pageTimer.pause();
    const router = useRouter();
    const forms = reactive({
      loading: true,
      code: null as any,
      openId: '' as any,
      isPageHide: false,
      contentA:
        '<p style="text-align: left; font-size:13px;"><strong style="font-size:15px;">尊敬的家长： 您好！</strong></p><p style="text-align: left;">非常感谢您一直以来对学校工作给予的大力支持与密切关注。为深入贯彻教育部《关于全面实施学校美育浸润行动的通知》（教体艺〔2023〕5 号）文件精神，积极顺应艺术素质测评结果纳入中考的教育改革趋势，致力于让学生在在校期间熟练掌握 1 - 2 项艺术专长，全面提升学生的艺术素养。</p><p style="text-align: left;">我校计划在北京知勉公益基金会的支持下，启动音乐（器乐）课堂数字化转型工作。为了确保此项工作顺利开展，现向您详细介绍相关情况，并诚恳征询您的宝贵意见，学校将根据您的意见反馈决定开展与否。</p>', // 第一段
      contentB:
        '<p style="text-align: left;"><strong style="font-size:15px; color: #0B8BFE;">二、为什么要开展数字化转型</strong></p><p style="text-align: left;">1.解决学习难题：数字化转型将为乐器学习和练习制定明确标准，学生能实时知晓练习的对错，练习结果也可量化呈现，有效解决学生不会练、家长无法辅导的困扰。</p><p style="text-align: left;">2.适应教改趋势：随着教育改革的推进，艺术素质测评结果已逐步纳入中考，数字化转型将助力学生更好地适应这一变化，提升综合素养。</p><p style="text-align: left;">3.关注身心健康：乐器学习能成为学生缓解学习压力的有效途径，有助于学生保持身心健康，实现全面发展。</p><p style="text-align: left;"><br></p>', // 第二段
      contentC:
        '<p style="text-align: left;"><strong style="font-size:15px; color: #0B8BFE;">三、开展原则</strong></p><p style="text-align: left;">本次活动面向全体学生，完全遵循学生自愿参加的原则。</p><p style="text-align: left;">1.若学生选择参加转型，家长需自行为学生准备好自用的乐器（硬件）和“器乐数字 Ai”应用（软件，用于联通学校音乐课堂）两项学习工具。</p><p style="text-align: left;">2.若学生不参加转型，可继续按原有方式进行音乐课学习。</p>',
      contentD:
        '<p style="text-align: left;"><strong style="font-size:15px; color: #0B8BFE;">五、事项说明</strong></p><p style="text-align: left;">1.学校不涉及任何费用收取。学生所需的自用工具在市面上均可购买到，家长可自行根据实际情况为学生准备。</p><p style="text-align: left;">2.如学生有参加数字化转型的意愿，但存在特殊或特困情况，可先向学校进行登记，学校将尽力寻求资源协助家长解决。</p><p style="text-align: left;">在您了解上述内容后，请点击下一步进行意见填写：</p>',
      introductionVideo: 'https://oss.dayaedu.com/ktyq/02/1739345029052.mp4',
      introductionVideoTime: 117,
      coverImg: 'https://oss.dayaedu.com/ktyq/02/1739362815061.png',
      introductionVideo2: 'https://oss.dayaedu.com/ktyq/02/1739345326291.mp4',
      introductionVideoTime2: 111,
      coverImg2: 'https://oss.dayaedu.com/ktyq/02/1739324215341.png',
      player1: null as any,
      player2: null as any,
      player1Speed: 1,
      player2Speed: 1,
      videoLoading1: true,
      videoLoading2: true,
      meetingType: 'primarySchoolNo' as
        | 'primarySchoolNo'
        | 'primarySchoolYes'
        | 'juniorSchoolNo'
        | 'juniorSchool'
        | any,
      intentionInfo: null as any,
      contentShow: false
    });

    const showPopup = ref(false);
    const showPopupMessage = ref('');

    // 播放视频总时长
    const videoIntervalRef = useInterval(1000, { controls: true });
    videoIntervalRef.pause();

    const videoIntervalRef2 = useInterval(1000, { controls: true });
    videoIntervalRef2.pause();

    onMounted(async () => {
      forms.meetingType = route.query.type || forms.meetingType;
      forms.code = route.query.code || forms.code;
      // nextTick(() => {
      //   const videoRef: any = document.querySelector('#register-video')
      //   const videoRef2: any = document.querySelector('#register-video2')
      //   if(videoRef) {
      //     const rect = videoRef?.getBoundingClientRect()
      //     console.log(rect)
      //     videoRef.style.height = rect.width / 16 * 9 + 'px'
      //   }
      //   if(videoRef2) {
      //     const rect = videoRef2?.getBoundingClientRect()
      //     console.log(rect)
      //     videoRef2.style.height = rect.width / 16 * 9 + 'px'
      //   }
      // })
      try {
        // 判断是否获取微信code码
        if (!forms.code  && browser().weixin) return;
        const { data } = await request.get(
          '/edu-app/open/meetingQuestionSetting/detail?type=' +
            forms.meetingType +
            '&weChatCode=' +
            forms.code
        );
        if (data) {
          forms.contentA = data.contentA || forms.contentA;
          forms.contentB = data.contentB || forms.contentB;
          forms.contentC = data.contentC || forms.contentC;
          forms.contentD = data.contentD || forms.contentD;
          forms.openId = data.openId || forms.openId;
          sessionStorage.setItem('active-open-id', forms.openId);
          sessionStorage.removeItem('isWxcode');
        }
        forms.contentShow = true;
      } catch {
        forms.contentShow = true;
      }
      console.log('初始化视频', 111);
      forms.player1 = _initVideo('one', forms, videoIntervalRef);
      forms.player2 = _initVideo('two', forms, videoIntervalRef2);
    });

    const getAppIdAndCode = async (url?: string) => {
      try {
        // const { data } = await request.get(
        //   '/edu-app/open/paramConfig/wechatAppId'
        // );
        // // 判断是否有微信appId
        // if (data) {
        //   sessionStorage.setItem('isWxcode', '1');
        //   closeToast();
        //   goWechatAuth(data, url);
        // }

        sessionStorage.setItem('isWxcode', '1');
        closeToast()
        goWechatAuthTemp('wxccc2efd2678adbe3', url)
      } catch (e) {
        //
        console.log(e);
      }
    };

    if (browser().weixin) {
      //授权
      const openId = sessionStorage.getItem('active-open-id');
      forms.openId = openId;
      const code = getUrlCode();
      const isWxcode = sessionStorage.getItem('isWxcode');
      if (!code || isWxcode !== '1') {
        const newUrl =
          getHttpOrigin() +
          window.location.pathname +
          '#' +
          route.path +
          '?' +
          qs.stringify({
            ...route.query
          });
        getAppIdAndCode(newUrl);
        return '';
      } else {
        forms.code = code;

        // 获取微信分享签名
        weChatShare.getAppSignature()
      }
    }
    const nextSkip = () => {
      router.push({
        path: '/fill-questionnaire',
        query: {
          openId: forms.openId, //
          meetingType: forms.meetingType
        }
      });
    };
    const onPageShow = () => {
      console.log(forms.isPageHide, 'showInfo');
      if (forms.isPageHide) {
        //window.location.reload();
      }
    };
    // 处理监听页面返回不刷新的问题
    window.addEventListener('pageshow', onPageShow);

    const onPageHide = () => {
      console.log(forms.isPageHide, 'showInfo');
      forms.isPageHide = true;
    };
    window.addEventListener('pagehide', onPageHide);

    onUnmounted(() => {
      window.removeEventListener('pageshow', onPageShow);
      window.removeEventListener('pagehide', onPageHide);
      forms.player1?.pause();
      forms.player1?.src('');
      forms.player1?.dispose();
      forms.player2?.pause();
      forms.player2?.src('');
      forms.player2?.dispose();
    });
    return () => (
      <div class={styles['intention-page']}>
        <div
          class={[
            styles['content-box'],
            !forms.contentShow && styles.hideContent
          ]}>
          <div class={styles.contentBody} v-html={forms.contentA}></div>
          <div class={styles.contentBody}>
            <div class={styles.cbTitle}>
              一、什么是音乐（器乐）课堂数字化转型<span>（详见视频介绍）</span>
            </div>
            <div class={styles.videoBoxCon}>
              <div class={styles.videoBox}>
                <div class={[styles['video-content']]}>
                  <video
                    id="register-video"
                    class={styles['video']}
                    src={forms.introductionVideo}
                    playsinline={true}
                    poster={forms.coverImg}
                    preload="auto"></video>
                </div>
              </div>
            </div>
          </div>
          <div class={styles.contentBody} v-html={forms.contentB}></div>
          <div class={styles.contentBody} v-html={forms.contentC}></div>
          <div class={styles.contentBody}>
            <div class={styles.cbTitle}>
              四、什么是器乐数字 Ai<span>（详见视频介绍）</span>
            </div>
            <div class={styles.videoBoxCon}>
              <div class={styles.videoBox}>
                <div class={[styles['video-content']]}>
                  <video
                    id="register-video2"
                    class={styles['video']}
                    src={forms.introductionVideo2}
                    playsinline={true}
                    poster={forms.coverImg2}
                    preload="auto"></video>
                </div>
              </div>
            </div>
          </div>
          <div class={styles.contentBody} v-html={forms.contentD}></div>
        </div>

        {/* 是否在微信中打开 */}
        <OWxTip />

        {forms.openId && (
          <div class={styles.bottomBtn}>
            <p>
              在您了解上述内容后，<i>请点击下一步进行意见填写</i>
            </p>
            <img class={styles.nextBtn} src={nextBtn} onClick={nextSkip} />
          </div>
        )}
      </div>
    );
  }
});
