import { defineComponent, onMounted, onUnmounted, reactive, ref } from 'vue';
import styles from './index.module.less';
import { closeToast } from 'vant';
import { useRoute, useRouter } from 'vue-router';
import OWxTip from '@/components/m-wx-tip';
import { browser, getHttpOrigin } from '@/helpers/utils';
import qs from 'query-string';
import request from '@/helpers/request';
import { useInterval } from '@vueuse/core';
import 'tcplayer.js/dist/tcplayer.css';
import { _initVideo } from './initVideo';
import nextBtn from './images/next_btn.png';
import useWeChatShare from '@/hooks/useWeChatShare';
import useAuthCode from '@/hooks/useAuthCode';

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

    const authCode = useAuthCode();
    // // 获取微信Code
    // if (!authCode.onWeChatCode('GET') || !authCode.onWeChatCatchOpenId('GET')) {
    //   authCode.getWeChatAuthCode(
    //     getHttpOrigin() +
    //       window.location.pathname +
    //       '#' +
    //       route.path +
    //       '?' +
    //       qs.stringify({
    //         ...route.query
    //       })
    //   );
    // }

    // 页面定时
    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:
        '', // 第一段
      contentB:
        '', // 第二段
      contentC:
        '',
      contentD:
        '',
      contentE: null as any,
      introductionVideo: 'https://oss.dayaedu.com/ktyq/03/1742283035204.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,
      tenantId: null as any // 机构id
    });

    // 播放视频总时长
    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.tenantId = route.query.id || '1891864516088385538';
      try {
        // getHttpOrigin() +
        //     window.location.pathname +
        //     '#' +
        //     route.path +
        //     '?' +
        //     qs.stringify({
        //       ...route.query
        //     })
        // const openId = await authCode.getOnlyOpenId();
        // forms.openId = openId;
        forms.openId = authCode.onWeChatCatchOpenId('GET');
        // console.log(forms.openId, 'openId - show');

        // 获取微信分享签名
        weChatShare.getAppSignature();
        // if (!browser().weixin || !openId) return;
        const { data } = await request.get(
          '/edu-app/open/meetingQuestionSetting/detail?type=' +
            forms.meetingType +
            '&tenantId=' +
            forms.tenantId
        );
        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.contentE = data.contentE || null;
          // 如果设置了题目名称，则存储，下一步页面需要用到
          if (forms.contentE) {
            sessionStorage.setItem('customQuestionE', forms.contentE);
          }
        }
        forms.contentShow = true;
      } catch {
        forms.contentShow = true;
      }
      console.log('初始化视频', 111);
      forms.player1 = _initVideo('one', forms, videoIntervalRef);
      forms.player2 = _initVideo('two', forms, videoIntervalRef2);
    });

    const nextSkip = () => {
      router.push({
        path: '/fill-questionnaire',
        query: {
          openId: forms.openId, //
          meetingType: forms.meetingType,
          tenantId: forms.tenantId
        }
      });
    };
    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} style="font-size:15px;">
              <strong>一、数字化音乐课堂介绍</strong>
            </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}>
            <div v-html={forms.contentC}></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 class={styles.contentBody}>
            <div class={styles.cbTitle} style="font-size:15px;">
              <strong>四、什么是器乐数字 Ai</strong><span style="font-size:13px;">（详见视频介绍）</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.contentA}></div>
          <div class={styles.contentBody}>
            <div v-html={forms.contentB}></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.contentC}></div>
          <div class={styles.contentBody}>
            <div v-html={forms.contentD}></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>

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

        {forms.openId && (
          <div class={styles.bottomBtn}>
            <p>
              <i>请点击下一步填写问卷</i>
            </p>
            <img class={styles.nextBtn} src={nextBtn} onClick={nextSkip} />
          </div>
        )}
      </div>
    );
  }
});
