<template>
  <div>
    <!-- <iframe :src="src" ref="iframe" id="iframe" style="border: 0px" width="500" height="480"></iframe> -->
    <canvas id="GameCanvas" oncontextmenu="event.preventDefault()" ref="iframe"></canvas>
    <div @click="sendOneAction(1)">hhhhhhhhhhhhhhhhhhhhhhh</div>
    <!-- <div @click="stepBtn">方法</div> -->
  </div>
</template>

<script>
import { sendToChain } from "./../../utils/chainapi.js";
import { getToken } from './../../utils/cookies.js'
import { isWalletConnected } from './../../wallet/index.js'
import {
  apiGameStep,
  apiPreStep,
} from "./../../utils/webapi.js";

export default {
  props: {
    getTotalUsed: Number,
  },
  data() {
    return {
      token: getToken(),
      // currIndex: localStorage.getItem('currIndex')
      currIndex: 0,
      awardData: {
        score: 20, //获得积分数量
        chest: [
          // { // 结构同 18.宝箱列表
          //   id: 1, // 箱子id
          //   stat: 0, // 0: 锁定, 1: 正常
          //   shareCode: '箱子的分享码',
          //   level: 1, // 箱子品级
          //   maxBonus: 10, // 最大可助力数量
          //   scoreInit: 5, // 初始可获得积分
          //   scoreBonus: 10, // 助力增加的分数
          //   bonusCount: 2, // 已助力次数
          // },
          // { // 结构同 18.宝箱列表
          //   id: 1, // 箱子id
          //   stat: 0, // 0: 锁定, 1: 正常
          //   shareCode: '箱子的分享码',
          //   level: 1, // 箱子品级
          //   maxBonus: 10, // 最大可助力数量
          //   scoreInit: 5, // 初始可获得积分
          //   scoreBonus: 10, // 助力增加的分数
          //   bonusCount: 2, // 已助力次数
          // }
        ],
      },
    };
  },
  created() {},
  mounted() {
    this.reload()
  },
  methods: {
    reload() {
      window.loadGame(()=>{
        window.boot()
      })
    },
    // 扔骰子
    randomdice() {
      //与后端交互的话在这一步进行扔骰子操作的请求，后端返回点数以及奖励，先拿点数进行走步操作，走步结束后，显示奖励详情
      return Math.round(Math.random() * 5 + 1); //随机生成1-6的整数
    },
    stepState(data) {
      console.log(data,'---------------------------------')
      setTimeout(
        cc.mainAnim.setCurrPos(this.getTotalUsed),
        4000)
    },
    async sendOneAction(step) {
      let address = this.$store.state.user.address;
      if (!this.$store.state.wallet.connected || !address) {
        console.log('====')
        throw new Error('wallet not connected')
      }
      const preRes = await apiPreStep(step)
      if (preRes.errcode) {
        this.$message.error(preRes.errmsg)
        return
      }
      let storeageKey
      try {
        storeageKey = await sendToChain('explore', address, preRes.data.id)
      } catch (err) {
        this.$message.error(`error send chain request`)
        return 
      }
      let serTimeId = setInterval(async () => {
        try {
          let { errcode, errmsg, data } = await apiGameStep(preRes.data.id)
          if (errcode) {
            if (errcode !== 13) {
              // 状态不是等待链上确认的, 都提示错误
              this.$message.error(errmsg)
              clearInterval(serTimeId)
            } 
          } else {
            alert(`领取成功, 播放动画, 并显示奖励: ${JSON.stringify(data)}`)
            // cc.mainAnim.setCurrPos(getTotalUsed)
            // cc.mainAnim.setData(step)
            // this.$emit('awardDialog', JSON.stringify(data))
            localStorage.removeItem(storeageKey)
            clearInterval(serTimeId)
          }
        } catch (err) {
          this.$message.error(`claim task reward error: ${err}`)
        }
      }, 3000)
    },
    // 行动
    async stepBtn(getTotalUsed,amount) {
      let myAddress = localStorage.getItem("myAddress")
      if(await isWalletConnected()) {
          if(amount >= 1) {
          cc.mainAnim.setCurrPos(getTotalUsed)
          cc.mainAnim.setData(amount)
          let res = await this.$axios.post('/api/game/pre_step',{step: amount},{headers: { Authorization: `Bearer ${this.token}` }})
          let id = res.data.data.id
          if(id){
            try{
              let result = await sendExplore(myAddress, id)
              if(result) {
                let serTimeId = setInterval(async () => {
                  let resExplore = await apiGameStep(id);
                  console.log(resExplore)
                  if(resExplore.data) {
                    console.log(resExplore.data)
                    this.$emit('awardDialog', this.awardData)
                    clearInterval(serTimeId)
                    // location.reload()
                  }
                }, 2000)
              }
          } catch(e) {
            this.$message.error(e.message)
          }
          }
        } else {
          this.$message.error('Get the number of explorations')
        }
      } else {
        this.$message.error('Log in first')
      }
    },

  }
};
</script>

<style lang="scss" scoped>
#GameCanvas {
  
}
</style>