import { Button, Icon, Popup, Swipe, SwipeItem, showDialog } from 'vant';
import {
  defineComponent,
  onMounted,
  reactive,
  onUnmounted,
  ref,
  Transition,
  watch,
  nextTick
} from 'vue';
import styles from './index.module.less';
import 'plyr/dist/plyr.css';
import request from '@/helpers/request';
import { state } from '@/state';
import { useRoute } from 'vue-router';
import iconBack from '../coursewarePlay/image/back.svg';
import {
  listenerMessage,
  postMessage,
  promisefiyPostMessage
} from '@/helpers/native-message';
// import { browser } from '@/helpers/utils';
import { Vue3Lottie } from 'vue3-lottie';
import playLoadData from '../coursewarePlay/datas/data.json';
// import { handleCheckVip } from '../hook/useFee';
import VideoClass from './video-class';
import { usePageVisibility } from '@vant/use';
import { useInterval, useIntervalFn } from '@vueuse/core';
import { handleCheckVip, hasVip } from '../hook/useFee';

// const materialType = {
//   视频: 'VIDEO',
//   图片: 'IMG',
//   曲目: 'SONG'
// };

export default defineComponent({
  name: 'exercise-after-class',
  setup() {
    const pageVisibility = usePageVisibility();
    /** 设置播放容器 16:9 */
    const parentContainer = reactive({
      width: '100vw'
    });
    const setContainer = () => {
      const min = Math.min(screen.width, screen.height);
      const max = Math.max(screen.width, screen.height);
      const width = min * (16 / 9);
      if (width > max) {
        parentContainer.width = '100vw';
        return;
      } else {
        parentContainer.width = width + 'px';
      }
    };
    const handleInit = (type = 0) => {
      setContainer();
      // 横屏
      postMessage({
        api: 'setRequestedOrientation',
        content: {
          orientation: type
        }
      });
      // 安卓的状态栏
      postMessage({
        api: 'setStatusBarVisibility',
        content: {
          isVisibility: type
        }
      });
    };
    handleInit();
    onUnmounted(() => {
      handleInit(1);
    });

    const route = useRoute();
    const query = route.query;
    const headeRef = ref();
    const data = reactive({
      disableScreenRecordingFlag: '0', // disable recording
      visiableStatus: false,
      visiableConfirmText: '下一题',
      isLastIndex: false,
      itemIndex: 0,
      isMember: false, // 是否为会员
      videoData: null as any,
      trainings: [] as any[],
      expireTimeFlag: false, // 作业是否结束
      trainingTimes: 0,
      itemList: [] as any,
      showHead: true,
      loading: true,
      recordLoading: false,
      isPlayBaseStatus: true, // 初始状态是否播放完
      isPlayAll: true // 是否全部做完
    });
    const activeData = reactive({
      nowTime: 0,
      model: true, // 遮罩
      timer: null as any,
      item: null as any
    });
    // 获取课后练习记录
    const getTrainingRecord = async () => {
      try {
        // ?${query.courseScheduleId}?userId=${state.user?.data?.id}
        const res: any = await request.post(
          state.platformApi +
            `/studentCourseHomework/findStudentHomeworkCourseware`,
          {
            hideLoading: true,
            data: {
              courseScheduleId: query.courseScheduleId,
              type: query.type
            }
          }
        );
        // data.expireTimeFlag = res.data?.expireTimeFlag || false;
        if (Array.isArray(res?.data)) {
          const trainings = res?.data || [];
          //   const tempLessonTraining: any = [];
          //   trainings.forEach((item: any) => {
          //     tempLessonTraining.push(
          //       ...(item.studentLessonTrainingDetails || [])
          //     );
          //   });
          // 没有播放完
          trainings.forEach((item: any) => {
            if (item.times > item.trainingTimes) {
              data.isPlayAll = false;
            }
            if (item.id + '' == route.query.materialId) {
              popupData.tabName = item.musicScoreName;
            }
          });
          return trainings;
        }
      } catch (error) {
        //
      }
      return [];
    };
    const setRecord = async (trainings: any[]) => {
      if (Array.isArray(trainings)) {
        data.trainings = trainings.map((n: any) => {
          // const materialRefs = n.materialRefs ? n.materialRefs : [];
          // const materialMusicId =
          //   materialRefs.length > 0 ? materialRefs[0].resourceId : null;
          return {
            ...n,
            // materialMusicId,
            currentTime: 0,
            duration: 100,
            paused: true,
            loop: false,
            videoEle: null,
            timer: null,
            muted: hasVip() ? false : true, // 静音
            // muted: true,
            autoplay: hasVip() ? true : false //自动播放
          };
        });
        // console.log(data.trainings, 'trainings', hasVip());
        data.itemList = data.trainings.filter(
          (n: any) => n.id == route.query.materialId
        );
        data.videoData = data.itemList[0];
        // console.log(data.videoData, '1212112', data.itemList);
        if (data.disableScreenRecordingFlag === '1') {
          // 检测是否录屏
          handleLimitScreenRecord();
        }
        handleExerciseCompleted();
      }
    };

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

    // 更新时间
    const updateStat = async () => {
      try {
        // 只有学生才统计数据
        if (state.platformType === 'STUDENT') {
          const videoTime = videoIntervalRef.counter.value;
          if (videoTime <= 0) return;
          videoIntervalRef.counter.value = 0;
          await request.post(
            `${state.platformApi}/studentCoursewarePlayRecord/save`,
            {
              data: {
                playTime: videoTime
              }
            }
          );
        }
      } catch {
        //
      }
    };

    // 获取支付渠道
    const sysParamConfig = async () => {
      try {
        const res = await request.get(
          state.platformApi + '/sysConfig/queryByParamName',
          {
            params: {
              paramName: 'disable_screen_recording_flag'
            }
          }
        );
        data.disableScreenRecordingFlag = res.data.paranValue || '';
      } catch {
        //
      }
    };

    let timers: any = null;
    const checkVideoPlay = () => {
      const activeVideoRef = data.videoData?.videoEle;
      if (activeVideoRef) {
        timers = setInterval(() => {
          if (!activeVideoRef.paused()) {
            activeVideoRef.pause();
            clearInterval(timers);
          }
          activeVideoRef.pause();
        }, 100);
      }
      setTimeout(() => {
        clearInterval(timers);
      }, 3000);
    };
    // 切换播放
    const togglePlay = (m: any, isPlay: boolean) => {
      if (isPlay) {
        m.videoEle?.play();
      } else {
        m.videoEle?.pause();
      }
    };
    //录屏时间触发
    const handleLimitScreenRecord = async () => {
      const result = await promisefiyPostMessage({
        api: 'getDeviceStatus',
        content: { type: 'video' }
      });
      const { status } = result?.content || {};
      if (status == '1') {
        data.itemList.forEach((item: any) => (item.autoPlay = false));
        handleStopVideo();
        // 处理事件 - 事件事件后加载的
        checkVideoPlay();
        data.visiableStatus = false;
        showDialog({
          title: '温馨提示',
          message: '课件内容请勿录屏',
          beforeClose: () => {
            return new Promise(resolve => {
              promisefiyPostMessage({
                api: 'getDeviceStatus',
                content: { type: 'video' }
              }).then((res: any) => {
                const content = res.content;
                if (content?.status == '1') {
                  togglePlay(data.videoData, false);
                  resolve(false);
                } else {
                  togglePlay(data.videoData, true);
                  resolve(true);
                }

                handleExerciseCompleted();
              });
            });
          }
        });
      }
    };
    onMounted(async () => {
      await sysParamConfig();
      const trainings = await getTrainingRecord();
      // 初始化状态
      // console.log(trainings, 'trainings');
      setRecord(trainings);
      // 是否为会员
      if (state.platformType === 'STUDENT') {
        data.isMember = handleCheckVip();
        // console.log(data.isMember, 'isMember');
        if (!data.isMember) {
          nextTick(() => {
            postMessage({
              api: 'courseLoading',
              content: {
                show: false,
                type: 'fullscreen'
              }
            });
          });
          return;
        }
      }

      if (data.disableScreenRecordingFlag === '1') {
        //禁止录屏 ios
        listenerMessage('setVideoPlayer', result => {
          if (result?.content?.status == 'pause') {
            handleLimitScreenRecord();
          }
        });
        // 安卓
        postMessage({
          api: 'limitScreenRecord',
          content: {
            type: 1
          }
        });
      }
      // 只有学生才统计数据
      if (state.platformType === 'STUDENT') {
        // 间隔多少时间同步数据
        intervalFnRef.value = useIntervalFn(async () => {
          // 同步数据时先进行有效时间进行保存
          // initVideoCount(false, true);
          await updateStat();
        }, 5000);
      }
    });
    // 返回
    const goback = () => {
      postMessage({ api: 'back' });
    };

    const swipeRef = ref();
    const popupData = reactive({
      firstIndex: 0,
      open: false,
      activeIndex: -1,
      tabActive: '',
      tabName: '',
      itemActive: '',
      itemName: ''
    });

    // 达到指标,记录
    const addTrainingRecord = async () => {
      if (data.recordLoading || data.expireTimeFlag) return;
      console.log('记录观看次数');
      data.recordLoading = true;
      const body = {
        id: data.videoData?.id || ''
      };
      try {
        await request.get(
          state.platformApi + '/studentCourseHomework/addStudentHomeworkRecord',
          {
            params: body,
            hideLoading: true
          }
        );
      } catch (error) {
        //
      }
      data.recordLoading = false;
      try {
        const trainings: any[] = await getTrainingRecord();
        if (Array.isArray(trainings)) {
          const item = trainings.find((n: any) => n.id == data.videoData?.id);
          // console.log(item, 'item');
          if (item) {
            data.videoData.trainingTimes = item.trainingTimes;
            handleExerciseCompleted();
          }
        }
      } catch (error) {
        //
      }
    };
    // 停止所有的播放
    const handleStopVideo = () => {
      data.itemList.forEach((m: any) => {
        m.videoEle?.pause();
      });
    };

    // 判断练习是否完成
    const handleExerciseCompleted = () => {
      if (
        data?.videoData?.trainingTimes != 0 &&
        data?.videoData?.trainingTimes >= data.videoData?.times
      ) {
        let isLastIndex = false;
        let itemIndex = 0;
        // console.log(data.isPlayBaseStatus, data.isPlayAll, data.trainings);
        // if (data.isPlayBaseStatus) {
        //   itemIndex = data.trainings.findIndex(
        //     (n: any) => n.id == data.videoData?.id
        //   );
        //   isLastIndex = itemIndex === data.trainings.length - 1;
        // } else {
        let i = -1;
        let status = true;
        data.trainings.forEach((item: any, index: number) => {
          if (item.times > item.trainingTimes && i === -1) {
            i = index;
          }
          if (item.times > item.trainingTimes) {
            status = false;
          }
        });
        itemIndex = i != -1 ? i - 1 : -1;
        isLastIndex = status;
        // }

        data.visiableConfirmText = isLastIndex ? '完成' : '下一题';
        data.visiableStatus = true;
        data.itemIndex = itemIndex;
        console.log(itemIndex, 'index');
        data.isLastIndex = isLastIndex;
      }
    };

    const dialogConfirm = () => {
      if (!data.isLastIndex) {
        const nextItem = data.trainings[data.itemIndex + 1];
        if (nextItem.musicScoreName) {
          popupData.tabName = nextItem.musicScoreName;
        }
        data.itemList = [nextItem];
        data.videoData = nextItem;
        handleExerciseCompleted();
      } else {
        postMessage({ api: 'goBack' });
      }

      data.visiableStatus = false;
    };
    const dialogCancel = () => {
      try {
        // data.trainings[data.itemIndex].currentTime = 0;
      } catch (e) {
        //
      }
      data.visiableStatus = false;
    };

    watch(pageVisibility, (value: any) => {
      handleStopVideo();
      if (value == 'visible') {
        // 横屏
        postMessage(
          {
            api: 'setRequestedOrientation',
            content: {
              orientation: 0
            }
          },
          () => {
            // console.log(234);
          }
        );
      }
    });

    return () => (
      <div class={styles.playContent}>
        <div
          class={styles.coursewarePlay}
          style={{ width: parentContainer.width }}>
          <Swipe
            style={{ height: '100%' }}
            ref={swipeRef}
            showIndicators={false}
            loop={false}
            vertical
            lazyRender={true}
            touchable={false}
            duration={0}>
            {data.itemList.map((m: any) => {
              return (
                <SwipeItem>
                  <>
                    <VideoClass
                      item={m}
                      isMember={data.isMember}
                      modal={activeData.model}
                      onSeeked={() => {
                        videoIntervalRef.isActive.value &&
                          videoIntervalRef.pause();
                      }}
                      onSeeking={() => {
                        videoIntervalRef.isActive.value &&
                          videoIntervalRef.pause();
                      }}
                      onWaiting={() => {
                        videoIntervalRef.isActive.value &&
                          videoIntervalRef.pause();
                      }}
                      onTimeupdate={() => {
                        const activeVideoRef = m.videoEle;
                        if (
                          !videoIntervalRef.isActive.value &&
                          activeVideoRef?.currentTime() > 0 &&
                          !activeVideoRef?.paused()
                        ) {
                          videoIntervalRef.resume();
                        }
                      }}
                      onPause={() => {
                        clearTimeout(activeData.timer);
                        activeData.model = true;
                        videoIntervalRef.pause();
                        console.log('11111');
                      }}
                      onEnded={() => addTrainingRecord()}
                      onChangeModal={(status: boolean) => {
                        activeData.model = status;
                      }}
                    />
                    {m.muted && (
                      <div class={styles.loadWrap}>
                        <Vue3Lottie animationData={playLoadData}></Vue3Lottie>
                      </div>
                    )}
                  </>
                </SwipeItem>
              );
            })}
          </Swipe>

          <Transition name="top">
            {activeData.model && (
              <div class={styles.headerContainer} ref={headeRef}>
                <div class={styles.backBtn} onClick={() => goback()}>
                  <Icon name={iconBack} />
                  返回
                </div>
                <div class={styles.menu}>{popupData.tabName}</div>
                <div class={styles.nums}>
                  练习次数：{data.videoData?.trainingTimes || 0}/
                  {data.videoData?.times || 0}
                </div>
              </div>
            )}
          </Transition>
        </div>

        <Popup
          v-model:show={data.visiableStatus}
          // closeable
          class={styles.visiablePopup}
          closeOnClickOverlay={false}>
          <div class={styles.title}>温馨提示</div>
          <p class={styles.content}>您已完成该练习～</p>
          <div class={styles.btnGroup}>
            <Button round block onClick={dialogCancel}>
              继续
            </Button>
            <Button color="#01C1B5" round block onClick={dialogConfirm}>
              {data.visiableConfirmText}
            </Button>
          </div>
        </Popup>
      </div>
    );
  }
});
