<template>
  <div :class="['game-container', { 'is-gaming': isGaming }]">
    <div ref="ui" :class="['ui']">
      <i class="ui__bg-layout"/>
      <router-view v-slot="{ Component }">
        <transition name="slide" mode="out-in">
          <component :is="Component"/>
        </transition>
      </router-view>
    </div>
    <div :id="containerId" class="game-container__inner"/>
  </div>
</template>

<script>
import eventEmitter from "@/eventEmitter"
import {mapActions} from "vuex"
import localforage from 'localforage'
import {createOperatePHX} from "@/sdk/operateBZPHX";

export default {
  name: "App",
  data() {
    return {
      //downloaded: false,
      gameInstance: null,
      containerId: 'carefree-container',
    }
  },
  computed: {
    isGaming() {
      return true
    },
  },
  async mounted() {
    localforage.config({
      name: 'carefree'
    });
    const game = await import('@/game/')
    this.stopHandlersFromUI()
    this.setEvents()
    await this.$router.push({name: 'home'})
    this.gameInstance = game.launch('carefree-container')
    eventEmitter.emit("phaser:startGame")
  },
  methods: {
    ...mapActions([
      'getUser',
      'setUser',
      'addUser',
    ]),

    stopHandlersFromUI() {
      const ui = this.$refs.ui;
      if (!ui) return setInterval(() => this.stopHandlersFromUI(), 16);

      const events = ['mousedown', 'mouseup', 'touchstart', 'touchmove', 'touchend', 'touchcancel']
      for (const eventName in events) {
        ui.addEventListener(eventName, e => e.stopPropagation())
      }
    },

    setEvents() {
      eventEmitter.on("vue:home", () => {
        this.$router.push({name: "home"});

        this.getUser().then(localUser => {
          // 初始化
          createOperatePHX().then(opePHX => {
            opePHX.initSDK('40009', 0, true,
                ({event, isLogin, user}) => {
                  switch (event) {
                    case 'init_finished': // 初始化完成
                      if (!(localUser && localUser.username)) {
                        if (isLogin) {
                          let newUser = {id: user.uid, username: user.name,};
                          this.addUser(newUser);
                          opePHX.readArchive(({data}) => {  // 读取存档
                            let json = JSON.parse(Buffer.from(data, 'base64').toString());
                            const {role} = json;
                            if (role?.length)
                              newUser.role = role;
                            // todo: 读取存档，更新角色信息
                          })
                        }
                      }
                      break;
                    case 'account_logout': // 账号登出
                      this.addUser({})
                      break;
                    case 'account_switch': // 账号切换
                      break;
                    default:
                  }
                  this.$router.push({name: "userInfo"})
                });
          });
        });
      })
    },

  },
  destroyed() {
    //this.gameInstance.destroy(false)
  },
}
</script>

<style lang="scss">
.game-container {
  position: relative;
  overflow: hidden;

  @media screen and (max-width: 600px) {
    padding-bottom: 15px;
  }

  &__inner {
    width: 100%;
    height: 100%;

    display: flex;
    align-items: center;
    justify-content: center;

    canvas {
      max-width: 100%;
      max-height: 100%;

      filter: blur(20px);

      transition: .3s;

      .is-gaming & {
        filter: none;
      }
    }
  }
}

.ui {
  &__bg-layout {
    content: "";
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, .5);

    transition: .3s;

    .is-gaming & {
      opacity: 0;
      visibility: hidden;
      pointer-events: none;
    }
  }

}

.preload-text {
  display: flex;
  align-items: center;
  justify-content: center;

  height: 100vh;

  font-size: min(1rem, 7vw);
}

.slide {

  &-enter-active,
  &-leave-active {
    transition: .2s;
  }

  &-enter-from,
  &-leave-to {
    transform: translateY(-100%);
  }
}
</style>
