<template>
  <view
    class="game-view"
    id="game-view"
  >
  <!--  :style="`pointer-events: ${state.mode === CardModeEnum.PREVIEW ? 'none' : 'all'}`" -->
    <navbar
      @goback="goback"
      @changeMagnifier="changeMagnifier"
      :="{
        ...navbarState,
        levelCount: state.cardIds.length
      }"
    />
    <view class="luojigou-board-box">

      <luojigou-board
        :key="state.cardId"
        v-if="state.card?.board?.quesUrl"
        :cardType="state.card?.cardType"
        :board="state.card?.board"
        :mode="state.mode"
        :tipsButton="state.card.tipsButton"
        :cardDesc="state.card.cardDesc"
        :playLoading="state.playLoading"
        :audioSrc="state.card.audio"
        :magnifierState="state.magnifierState"
        @playAudio="playAudio"
        @submit="onSubmitCard"
      />

    </view>

    <rive-ani ref="riveAniRef" :key="navbarState.progress" />

  </view>

  <!-- <view class="device-dire-tip"  v-if="device.dire === 'H'" >
    <rotate-tip />
  </view>  -->


  <img v-if="state.mode === CardModeEnum.OPRA && gamePlayed" style="width: 100vw;height: 100vh;position: fixed; z-index: 1000000;scale: 1;" :src="staticImg.intro" alt="">
</template>


<script setup lang="ts" >

import { CardModeEnum, OpraModeEnum } from '@/enum/constant';
import { onLoad } from '@dcloudio/uni-app';
import { reactive, onMounted } from 'vue'
import { getCardDetailById, submitlearnPortAns } from '@/api/card'
import { getCollectionDetailById } from '@/api/collection'
import { useAudioMange, useScheduler, useBase64, useSchedulerOnce, usePlatform, useDeviceDire,useGyro } from '@/hooks/index'
import { usePracticeStore, useOpraRecordStore, useGameCountdownStore, useCalcQuantityStore, useWisdomCoinStore } from '@/store'
import riveAni from '@/components/rive-ani/rive-ani.vue';
import { ref } from 'vue';
import { useAppBridge } from '@/hooks/app';
import { useStaticImg } from '@/hooks/index';

/**
 *  README.md 里有详细的参数说明
 */
export interface QueryParams {
  mode: CardModeEnum,
  collectionId: string,
  cardId?: string,
  opraMode: OpraModeEnum,
}

interface State extends QueryParams {
  card: Partial<API.Card> | null,
  cardIds: string[],
  playLoading: boolean,
  userCardAnswerList: any[],
  queryParams: API.P | null,
  magnifierState: boolean
}

const atx = useAudioMange()

const practiceStore = usePracticeStore()

const opraRecordStore = useOpraRecordStore()

const gameCountdownStore = useGameCountdownStore()

const calcQuantityStore = useCalcQuantityStore()

const wisdomCoinStore = useWisdomCoinStore()
const base64 = useBase64()

const staticImg = useStaticImg()

useGyro()

onLoad(query => {

  let options
  if (import.meta.env.MODE === "development") {
    state.queryParams = base64.decode<API.P>(query!.p)
    state.opraMode = state.queryParams.data.opraMode
    options = state.queryParams.data
  } else {
    state.queryParams = base64.decode<API.P>(query!.p)
    state.opraMode = state.queryParams.data.opraMode
    options = state.queryParams.data
    // options = query!
  }
  
  state.mode = options.mode || CardModeEnum.PREVIEW
  state.collectionId = options.collectionId
  if (options.cardId) state.cardId = options.cardId

  wisdomCoinStore.total = options.userWisdomCoin
  wisdomCoinStore.remainderWisdomCoin = options.remainderWisdomCoin
})

const riveAniRef = ref()

// 0 代表已经播放过了 1 代表没有播放过
const gamePlayed = ref<0 | 1>( uni.getStorageSync('played') ? 0 : 1)

const navbarState = reactive({
  progress: 1,
  countdownTotal: 0,
  mode: CardModeEnum.PREVIEW
})

const device = reactive({
  dire: ''
})

const state = reactive<State>({
  opraMode: OpraModeEnum.COMPE,
  mode: CardModeEnum.PREVIEW,
  collectionId: '',
  cardIds: [],
  cardId: '',
  card: {
    board: {
      quesUrl: '',
      ansUrl: '',
      buttons: [],
      ansList: []
    }
  },
  playLoading: false,
  userCardAnswerList: [],
  queryParams: null,
  magnifierState: false
})

const stx = useScheduler(() => {
  
  navbarState.countdownTotal++
}, 1000)


const getIntro = () => {
  // 先判断有没有玩过，如果没有玩过
  if (state.mode === CardModeEnum.OPRA) {
    const played = uni.getStorageSync('played')
    console.log('played:',played);
    
    if (!played) {
      uni.setStorageSync('played', 1)
      useSchedulerOnce(() => {
        gamePlayed.value = 0
        gameStart()
      }, 6000)
    } else {
      gameStart()
    }
  } else {
    gameStart()
  }
}

// 控制是否开启动画模式
const changeMagnifier = (status: boolean) => {
  state.magnifierState = status
}

// 控制游戏开始
const gameStart = () => {
  navbarState.countdownTotal = 0
  playAudio()
  if (device.dire === 'V') {
    stx.start()
  }
  
}

// 提交单张题卡数据
const onSubmitCard = async () => {

  stx.stop()

  // 触发做题完成的动画
  await riveAniRef.value.start(calcQuantityStore.getStar(), state.card?.cardType)

  wisdomCoinStore.itemCoin += calcQuantityStore.getStar()

  // 保存做题记录
  opraRecordStore.push({
    correctQuantity: calcQuantityStore.correctQuantity,
    totalQuantity: calcQuantityStore.totalQuantity,
    wrongCount: calcQuantityStore.wrongCount,
    capability: state.card?.cardAble
  })

  // 保存做题时间
  gameCountdownStore.sum(navbarState.countdownTotal)

  // 触发游戏结束
  if (navbarState.progress == state.cardIds.length) {

    gameCompleted()

    return
  }

  // 切换题卡

  if (state.opraMode == OpraModeEnum.PRACTICE) {

    // state.cardId

  } else {
    navbarState.progress++

    state.cardId = state.cardIds[navbarState.progress - 1]
  }

  calcQuantityStore.clear()
  
  GetCardDetailById()
}

// 提交题卡
const gameCompleted = async () => {
  // state
  const $par = {
    "attach": {
      "itemId": state.queryParams?.attach.itemId,
      "recordId": state.queryParams?.attach.recordId
    },
    "data": {
      "correctQuantity": opraRecordStore.totalCorrectQuantity(),
      "gameDuration": gameCountdownStore.get(),
      "totalQuantity": opraRecordStore.totalQuantity(),
      "userCardAnswerList": opraRecordStore.get(),
      "winWisdomCoin":  wisdomCoinStore.itemCoin
    }
  }

  const data = await submitlearnPortAns($par, state.queryParams?.submitUrl!)
  
  opraRecordStore.clear()

  // 如果opraMode 的是learn 则跳转到app-web页面
  if (state.opraMode == OpraModeEnum.LEARN) {

    window.location.href = `https://nginx.test.luojigou.vip/app_web/learn-plan.html#/?from='exercise'`
  }
  
}

const playAudio = () => {
  
  state.playLoading = true
  atx.play(state.card?.audio!)
  atx.onplayend(() => state.playLoading = false)
}

// 获取试题集详情
const GetCollectionDetailById = async () => {
  const { data } = await getCollectionDetailById(state.collectionId)
  if ( state.opraMode === OpraModeEnum.PRACTICE) {
    state.cardIds = practiceStore.get(state.collectionId, data.cardIds)
    state.cardId = practiceStore.nextId(state.cardIds)
  } else {
    state.cardIds = data.cardIds
  }

  if ( state.cardIds.length > 0) {
    state.cardId = state.cardIds[navbarState.progress - 1]
    GetCardDetailById()
  }
}

// 获取题卡详情
const GetCardDetailById = async () => {
  const { data } = await getCardDetailById(state.cardId!, state.mode)
  state.card = data
  if (state.mode === CardModeEnum.OPRA) {
  }
}

// 返回上一级菜单 学习计划是返回 app 大赛是返回上一级路由
const goback = () => {
  if (usePlatform() == 'web') {
    useAppBridge().back()
  } else {
    // 返回上一级路由
  }
}

// 监听设备方向，如果是横屏，立马停止所有的计时
useDeviceDire((dire: 'H' | 'V') => {
  if (device.dire == 'H' && dire === 'V') {
    stx.start()
  } 
  device.dire = dire
  
  if (dire === 'H') {
    stx.pause()
  }
})

onMounted(async () => {

  if (state.mode === 'preview') {
    await GetCardDetailById()
  } else {
    await GetCollectionDetailById()
  }
  getIntro()
})

</script>


<style lang="less" scoped >
.game-view {
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  background: rgba(251, 223, 172, 1);
  position: fixed; position: -ms-device-fixed;
  top: 0px; left: 0px; right: 0px; bottom: 0px;
  .luojigou-board-box {
    width: 100vw;
    height: 708px;
    background: url('https://app-resources-luojigou.luojigou.vip/Fqj0sowjX078sk3PgbBlSvT_Ti9R');
    display: flex;
    justify-content: center;
    padding-top: 46rpx;
    display: flex;
    justify-content: center;
  }
}

.device-dire-tip {
  width: 100vw;
  height: 100vh;
  background-color: rgba(0, 0, 0, 0.3);
  position: fixed;
  top: 0;
  left: 0;
  z-index: 1000;
  pointer-events: none;
  display: flex;
  justify-content: center;
  align-items: center;
  .tip {
    img {
      width: 180rpx;
      height: 180rpx;
    }
    .desc {
      font-size: 16rpx;
      font-family: PingFang SC-Regular, PingFang SC;
      font-weight: 400;
      color: #FFFFFF;
      line-height: 22rpx;
    }
  }
  
}
</style>